怎么给String.fromCharCode的参数传入变量

今天在研究js加密解密过程中,想做一个工具,发现只能给fromCharCode传以逗号间隔的数字,如何动态传入?

先来看一下 fromCharCode() 的定义和用法(属于String对象)

fromCharCode() 可接受一个或多个指定的 Unicode 值,然后返回一个字符串。

注意:该方法是 String 的静态方法,字符串中的每个字符都由单独的 Unicode 数字编码指定。使用语法: >String.fromCharCode()
method 所有主要浏览器都支持 fromCharCode() 方法

语法

String.fromCharCode(code1, code2, code3, …, codeN)

code1, code2, code3, …, codeN:必需。一个或多个 Unicode 值,即要创建的字符串中的字符的 Unicode 编码。

虽然下面这样的代码能执行

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

但是,如果我想用String.fromCharCode()转换外部输入的数据怎么办?

我尝试了这样一串代码

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

结果出乎意料的失败了.当我把它作为一个数组传递的时候,却不能运行。我也试着将数组转换为toString(),以及array.join(“,”); 创建一个逗号分隔列表…但没有任何结果。怎么解决?
后来经过查阅资料发现

JavaScript 函数 Apply
通过 apply() 方法,您能够编写用于不同对象的方法。

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

你也可以使用数组的reduce()方法,但是较老的IE不支持它。 但是这个apply()方法更好的支持。

var array = [72,69,76,76,79];
document.write(array.reduce(function(str, charIndex) {
	console.log(str)
	return str += String.fromCharCode(charIndex);
},''));

以上两种方法都能顺利输出 HELLO,问题完美解决

document.writeln(String.fromCharCode(65, 66, 67, 68, 69, 70)); //ABCDEF
document.write("<br>");
document.writeln(String.fromCharCode(101, 104, 97, 98, 122, 100)); //ehabzd
document.write("<br>");
document.writeln(String.fromCharCode(20013, 22269)); //中国

问题延伸

如果有大数据会提示内存溢出

return String.fromCharCode.apply(null, array);

替换

var res = '';
var chunk = 8 * 1024;
var i;
for (i = 0; i < array.length / chunk; i++) {
  res += String.fromCharCode.apply(null, array.slice(i * chunk, (i + 1) * chunk));
}
res += String.fromCharCode.apply(null, array.slice(i * chunk));
return res;

猜你喜欢

转载自blog.csdn.net/Sncdma/article/details/109894763