Can I pass an array into fromCharCode

China☆狼群 提交于 2019-11-28 21:14:44

You could use the function's apply() method...

document.write(String.fromCharCode.apply(null, array));

jsFiddle.

ES6 can use the spread operator...

document.write(String.fromCharCode(...array));

You could also use the array's reduce() method, but older IEs do not support it. You could shim it, but the apply() method is better supported.

document.write(array.reduce(function(str, charIndex) {
    return str += String.fromCharCode(charIndex);
}, ''));​

jsFiddle.

Yes, you can use apply() to call a function which an array passed in as its arguments:

array = [72,69,76,76,79];
document.write(String.fromCharCode.apply(String, array));

If you use .apply() to call the fromCharCode() function, you can pass it an array that will be converted into arguments for the function like this:

document.write(String.fromCharCode.apply(this, array));

You can see it work here: http://jsfiddle.net/jfriend00/pfLLZ/

Levi Hackwith

The method is more meant to be used like this:

document.write(String.fromCharCode(72,69,76,76,79));

You're passing in an array when the method expects multiple parameters as a list.

You may have to use a loop as follows

for(var i = 0; i < array.length; i++)
       document.write(String.fromCharCode(array[i]));
}

Here's 2 ways that I would do it:

var arr=[119,119,119,46,87,72,65,75,46,99,111,109];
document.write(eval('String.fromCharCode('+arr+')'));

document.write('<hr>');

var arr='119,119,119,46,87,72,65,75,46,99,111,109';
document.write(eval('String.fromCharCode('+arr+')'));

Here is a function:

var unCharCode = function(x) {
  return this["eval"]("String['fromCharCode'](" + x + ")");
};

document.write(unCharCode([ 119, 119, 119, 46, 87, 72, 65, 75, 46, 99, 111, 109 ]));

document.write("<hr>");

document.write(unCharCode("119,119,119,46,87,72,65,75,46,99,111,109"));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!