奇怪的输出[97,98] .map(String.fromCharCode) [英] Weird output of [97,98].map(String.fromCharCode)
问题描述
这按预期工作
[97,98].map(function(x){String.fromCharCode(x)})
// [ 'a', 'b' ]
但输出是以下行是意外的
but the output is following line is unexpected
[97,98].map(String.fromCharCode)
// [ 'a\u0000\u0000', 'b\u0001\u0000' ]
推荐答案
String.fromCharCode
可以接受可变长度的参数,并将每个参数视为字符代码以构建字符串参数。长度
字符长。
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
将多个参数传递给内部函数。第一个,显然是当前项目的价值。第二个是数组中的索引,这是 \\\
和 \\0001
来自(添加)更多字符代码,你得到 \ u0002
, \ u0003
...)。第三个参数是对正在遍历的数组的引用,它被转换为数字 0
。
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
.
来源: 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' ]
这篇关于奇怪的输出[97,98] .map(String.fromCharCode)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!