Weird output of [97,98].map(String.fromCharCode)

后端 未结 2 1604
清歌不尽
清歌不尽 2021-01-19 07:01

this works as expected

[97,98].map(function(x){String.fromCharCode(x)})
// [ \'a\', \'b\' ]

but the output is following line is unexpected<

相关标签:
2条回答
  • 2021-01-19 07:21

    String.fromCharCode can accept a variable length of arguments, and treats each one as a character code to build a string arguments.length characters long.

    map passes several arguments to the inner function. The first, obviously, is the value of the current item. The second is the index in the array, which is where the \u0000 and \u0001 come from (add more character codes and you get \u0002, \u0003...). The third argument is a reference to the array that is being traversed, which is converted to the number 0.

    Source: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map

    EDIT much, much later: An alternative approach:

    String.fromCharCode.apply(String, [97,98]);
    // [ 'a', 'b' ]
    
    0 讨论(0)
  • 2021-01-19 07:31
           a2 = [97,98].map(function(x){return String.fromCharCode(x)});
           alert(a2);
           a2 = [97,98].map(String.fromCharCode);
           alert(a2);
    

    both alert "a,b" for Firefox13 on Linux. the first function was missing a return statement.

    0 讨论(0)
提交回复
热议问题