非常有趣的问题。
答案是:你得到的原因3
最后是fromCharCode
返回一个字符串与调用中的参数一样多的字符到它,并且map
使用三个参数调用回调函数:元素的值、元素的索引以及正在遍历的对象。因此,一个字符串包含三个字符,但不是三个易于显示的字符。棘手。
具体来说,我们得到"C"
对于第一个参数;字符 0 代表第二个参数(因为我们正在考虑[0]
;它将是 1[1]
等),以及基于将数组强制转换为数字的字符(使用任何规则fromCharCode
用途; Šime Vidas 在下面说可以ToUInt16
上,这将导致0
).
因此,例如:
> String.fromCharCode(67, 0, [67, 65, 84]).length
3
...就像来自的电话一样map
.
为了清楚起见:
> String.fromCharCode(67, 0, [67, 65, 84]).length
3
> String.fromCharCode(67, 0, null).length
3
> String.fromCharCode(67, 0, 0, 0, 0, 0, 0).length
7
如果我们确保一次只传递一个参数,我们就不会看到那种意想不到的效果,所以当直接使用它时,会得到一个我认为大多数人都不会想到的结果:
> [67, 65, 84].map(String.fromCharCode)
["C", "A", "T"]
> [67, 65, 84].map(String.fromCharCode)[0]
"C"
> [67, 65, 84].map(String.fromCharCode)[0].length
3
...这给了我们一个更容易理解的结果:
> [67, 65, 84].map(function(value) { return String.fromCharCode(value); })
["C", "A", "T"]
> [67, 65, 84].map(function(value) { return String.fromCharCode(value); })[0]
"C"
> [67, 65, 84].map(function(value) { return String.fromCharCode(value); })[0].length
1