gpt4 book ai didi

JavaScript - fromCharCode 不是一个函数?

转载 作者:行者123 更新时间:2023-11-28 17:48:24 27 4
gpt4 key购买 nike

我正在尝试将十进制转换为如下文本:

function decimalToText(str){
var arr = [];
for (var i = 0, l = str.length; i < l; i ++) {
var text = str.fromCharCode(i);
arr.push(text);
}
return arr.join('');
}

例如,我希望将“104 101 108 108 111 32 119 111 114 108 100”转换为“hello world”

但我不断收到 Uncaught TypeError: str.fromCharCode is not a function

有人知道我哪里出错了吗?

最佳答案

你很接近。如果您查看 fromCharCode() 的文档您首先会发现您调用不正确

Because fromCharCode() is a static method of String, you always use it as String.fromCharCode(), rather than as a method of a String object you created.

您可以传入 unicode 字符数组并循环遍历它们,例如:

function decimalToText(unicodeArray){
var arr = [];
for (var index in unicodeArray) {
var text = String.fromCharCode(unicodeArray[index]);
arr.push(text);
}
return arr.join('');
}

console.log(decimalToText([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]));

或者更干净(无循环),您可以使用 apply function

function decimalToText(unicodeArray){
return String.fromCharCode.apply(null, unicodeArray);
}

console.log(decimalToText([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]));

或者使用 ES6,您可以使用 spread operator

function decimalToText(unicodeArray){
return String.fromCharCode(...unicodeArray);
}

console.log(decimalToText([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]));

关于JavaScript - fromCharCode 不是一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46185081/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com