28

我可能在这里问了错误的问题,所以如果答案在另一个线程上,我深表歉意......但我环顾四周无济于事。

在一个片段中,为什么这不起作用?

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

我正在一个数组中收集关键事件,并希望能够在出现提示时将它们写为字符。虽然这有效:

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

当我将它作为数组传递时,我似乎无法让它工作。我也尝试先将数组转换为 toString() 以及 array.join(","); 创建一个逗号分隔的列表......但什么都没有。有任何想法吗?有没有更好的方法将我在数组中收集的值转换为字符?

4

8 回答 8

42

您可以使用该函数的apply()方法...

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

js小提琴

ES6 可以使用扩展运算符...

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

您也可以使用数组的reduce()方法,但较旧的 IE 不支持它。您可以对其进行填充,但该apply()方法得到更好的支持。

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

js小提琴

于 2012-03-30T03:09:49.983 回答
10

是的,您可以使用apply()调用一个函数,该函数将数组作为其参数传入:

array = [72,69,76,76,79];
document.write(String.fromCharCode.apply(String, array));
于 2012-03-30T03:09:24.637 回答
3

如果你.apply()用来调用fromCharCode()函数,你可以传递一个数组,该数组将被转换为函数的参数,如下所示:

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

你可以在这里看到它的工作:http: //jsfiddle.net/jfriend00/pfLLZ/

于 2012-03-30T03:11:00.097 回答
1

该方法更适合这样使用:

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

当方法需要多个参数作为列表时,您将传入一个数组。

于 2012-03-30T03:09:34.877 回答
0

您可能必须使用如下循环

for(var i = 0; i < array.length; i++)
       document.write(String.fromCharCode(array[i]));
}
于 2012-03-30T03:17:07.227 回答
0

在新版本的 javascript 中,您可以使用spread syntax

const array = [72,69,76,76,79];
document.write(String.fromCharCode(...array));
于 2021-09-15T12:21:46.627 回答
-2

这是一个函数:

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

于 2016-01-14T08:43:16.627 回答
-2

这是我会做的两种方法:

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+')'));

于 2016-01-14T08:01:39.383 回答