在JavaScript中,在字符串上加入vs + =如何处理utf编码不同?

问题描述 投票:0回答:2

以下两个操作之间的区别是什么,一个操作以join产生"÷C ",另一个操作以reduce产生"÷C"

1

// returns "÷C "
["f7","43"].map(x=>'0x'+ x).map(String.fromCharCode).join('');

2

// returns "÷C"
["f7","43"].map(x=>'0x'+x).reduce((a, c) => { 
    a += String.fromCharCode(c); 
    return a 
}, '');
javascript ascii utf-16 fromcharcode
2个回答
1
投票

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提到的那样明确地做到这一点)


-1
投票

.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;
}, "");
© www.soinside.com 2019 - 2024. All rights reserved.