我可以将数组传递给fromCharCode [英] Can I pass an array into fromCharCode

查看:129
本文介绍了我可以将数组传递给fromCharCode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能会在这里提出错误的问题,所以如果答案是在另一个问题上,我会道歉......但我一直无所适从。

I might be asking the wrong question here, so I apologize if the answer is on another thread... but I've looked around to no avail.

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

in a snippet, why doesn't this work?

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

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

I'm collecting key events in an array and want to be able to write them out as chars when prompted. And though this works:

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

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

I can't seem to get it to work when I pass it along as an array. I've also tried to convert the array toString() first, as well array.join(","); to create a comma separated list ...yet nothing. Any ideas? Is there a better way to convert the values I collect in my array into chars?

推荐答案

您可以使用函数的 apply() method ...

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

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

jsFiddle

ES6可以使用点差运算符......

ES6 can use the spread operator...

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

您还可以使用数组的 reduce()方法,但较旧的IE不支持它。你可以 shim 它,但更好地支持 apply()方法。

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

这篇关于我可以将数组传递给fromCharCode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆