以下两个操作之间的区别是什么,一个操作以join
产生"÷C "
,另一个操作以reduce产生"÷C"
?
// returns "÷C "
["f7","43"].map(x=>'0x'+ x).map(String.fromCharCode).join('');
// returns "÷C"
["f7","43"].map(x=>'0x'+x).reduce((a, c) => {
a += String.fromCharCode(c);
return a
}, '');
String.fromCharCode
接受多个参数。每个参数将被解释为一个代码单元。在第一个代码中,由于.map
还提供了要遍历的索引和数组的参数:
["f7","43"].map(x=>'0x'+ x).map(String.fromCharCode).join('');
相当于
["f7","43"]
.map(x=>'0x'+ x)
.map((str, i, arr) => (
String.fromCharCode(str, i, arr)
)
.join('');
哪个结果出乎意料。
改为显式传递only str
,其结果将与第二个片段相同:
const result = ["f7","43"]
.map(x=>'0x'+ x)
.map((str) => (
String.fromCharCode(str)
))
.join('');
console.log(result);
((仍然用一个非数字的东西来调用fromCharCode
既奇怪又令人困惑,最好像Barmar提到的那样明确地做到这一点)
.reduce
将节省更多的迭代次数,其中您对[value]和[String.fromCharCode]进行的.map
比.join
大。因此reduce会比其他解决方案更快。
["f7", "43"]
.map((x) => "0x" + x) // O(n)
.map(String.fromCharCode) // O(n)
.join(""); // O(n)
// returns "÷C"
["f7", "43"]
.map((x) => "0x" + x) // O(n)
.reduce((a, c) => {
// O(n)
a += String.fromCharCode(c);
return a;
}, "");
// returns "÷C"
["f7", "43"].reduce((a, c) => { // O(n)
// O(n)
a += String.fromCharCode("0x" + c);
return a;
}, "");