简体   繁体   English

JavaScript + Chrome:String.fromCharCode提供多余的字符?

[英]JavaScript + Chrome: String.fromCharCode giving extraneous characters?

Can anyone explain why Chrome might be giving me this strange result? 谁能解释为什么Chrome可能会给我这个奇怪的结果? Defining, 定义

var chars = [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33];

this works just fine: 这很好用:

console.log(String.fromCharCode.apply(null,chars));

Hello, world! 你好,世界!

But

console.log(chars.map(String.fromCharCode));

returns 退货

["H", "e", "l", "l", "o", ",", " ", "w", "o", "r ", "l↵", "d?", "! "] [“ H”,“ e”,“ l”,“ l”,“ o”,“,”,“,” w“,” o“,” r“,”l↵“,” d?“, “!”

I didn't encounter this behavior in IE. 我在IE中没有遇到这种行为。 The "r " is a tab character. "r "是制表符。 It seems that Chrome will do this at the same position no matter what the input array/string is. 不管输入数组/字符串是什么,Chrome似乎都会在同一位置执行此操作。

The callback to [].map() receives three arguments: the current array item value, its index and the array itself. [].map()的回调接收三个参数:当前数组项的值,其索引和数组本身。 String.fromCharCode is a variadic function, hence it interprets all arguments as character codes. String.fromCharCode是可变参数函数,因此它将所有参数解释为字符代码。

That is, in the first iteration, you probably expect to get String.fromCharCode(72) (which is 'H' ), but in fact you're getting String.fromCharCode(72, 0, chars) === 'H\\x00\\x00' . 也就是说,在第一次迭代中,您可能希望得到String.fromCharCode(72) (它是'H' ),但实际上您正在得到String.fromCharCode(72, 0, chars) === 'H\\x00\\x00'

You can pass a callback function to ensure that only the array values are mapped to characters: 您可以传递一个回调函数以确保仅将数组值映射到字符:

chars.map(function(charCode) {
    return String.fromCharCode(charCode);
});

Don't forget that map does pass 3 arguments to its callback: The item, the index, and the array. 别忘了map确实将3个参数传递给其回调:项目,索引和数组。 That's the reason why you get "r\ " and "l\ " (or better known as "r\\t" and "l\\n" ) back in your array, from calls like String.fromCharCode.call(null, 114, 9, chars) and String.fromCharCode.call(null, 108, 10, chars) . 这就是为什么你的理由"r\ ""l\ " (或更好地称为"r\\t""l\\n" )早在你的阵列一样,来自电话String.fromCharCode.call(null, 114, 9, chars) String.fromCharCode.call(null, 108, 10, chars) String.fromCharCode.call(null, 114, 9, chars)String.fromCharCode.call(null, 108, 10, chars) The other strings will have a length of 2 as well, you just cannot see all those weird control characters in the output. 其他字符串的长度也将为2,您只是看不到输出中所有那些奇怪的控制字符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM