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

試著忘記壹切 提交于 2019-12-01 19:37:57

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' ]
       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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!