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

后端 未结 2 1605
清歌不尽
清歌不尽 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' ]
    

提交回复
热议问题