语句不起作用"/>
单行 reduce 语句不起作用
当我尝试使用注释代码(多行 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 语句?
回答如下:您可以将拆分后的字符串与匹配值作为索引进行映射。
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
更多推荐
单行 reduce 语句不起作用
发布评论