单行缩减语句无法运行 - 如何修复

3

当我尝试使用注释代码(多行reduce语句)时,它可以正常工作。 然而当我尝试使用单行reduce语句时,它却不能正常工作。 我理解这是由于reduce语句中的splice命令造成的。 有人能否建议如何克服这种情况以编写单行reduce语句?

function order(words){
    // ...
    let regex = /\d+/g;
    let matches = words.match(regex)

    // return words.split(' ').reduce((finalar, element, indx) => {
    //     console.log('matches', matches);
    //     finalar.splice(matches[indx] - 1, 0, element)
    //     console.log('element', element);
    //     return finalar;
    // }, []).join(' ');
    return words.split(' ').reduce((finalar, element, indx) => finalar.splice([matches[indx] - 1],0,element) , []);
}

console.log(order("is2 Thi1s T4est 3a"));  //Output: Thi1s is2 3a T4est

当我尝试使用注释代码(多行reduce语句)时,它可以正常工作。 然而,当我尝试使用单行reduce语句时,它不起作用。 我理解这是由于reduce语句中的splice命令造成的。 有人能否建议如何克服这种情况以编写单行reduce语句?


2
“splice” 返回已删除的项目。你需要使用 “reduce” 吗?为什么不映射一个新数组呢? - Nina Scholz
1个回答

1
你可以将分割后的字符串与匹配值作为索引进行映射。

function order(words) {
    const
        regex = /\d+/g,
        matches = words.match(regex);

    return words
        .split(' ')
        .map((_, i, a) => a[matches[i] - 1])
        .join(' ');
}

console.log(order("is2 Thi1s T4est 3a")); //Output: Thi1s is2 3a T4est


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接