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

查看:45
本文介绍了我可以将数组传递给 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));

当我将它作为数组传递时,我似乎无法让它工作.我也尝试先将数组转换为字符串(),以及 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() 方法...

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 不支持它.您可以填充它,但更好地支持 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天全站免登陆