Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

javascript - Can I pass an array into 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));

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...