mfvonh
mfvonh

Reputation: 195

JavaScript + Chrome: String.fromCharCode giving extraneous characters?

Can anyone explain why Chrome might be giving me this strange result? 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 ", "! "]

I didn't encounter this behavior in IE. The "r " is a tab character. It seems that Chrome will do this at the same position no matter what the input array/string is.

Upvotes: 2

Views: 1252

Answers (2)

Fabrício Matté
Fabrício Matté

Reputation: 70149

The callback to [].map() receives three arguments: the current array item value, its index and the array itself. String.fromCharCode is a variadic function, hence it interprets all arguments as character codes.

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

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);
});

Upvotes: 4

Bergi
Bergi

Reputation: 664538

Don't forget that map does pass 3 arguments to its callback: The item, the index, and the array. That's the reason why you get "r\u0009" and "l\u000a" (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). The other strings will have a length of 2 as well, you just cannot see all those weird control characters in the output.

Upvotes: 2

Related Questions