-1

I noticed that String.fromCharCode() does not work with a variable as parameter.

Here is some sample code:

var x = atob('ODAsNjUsODMsODMsODcsNzksODIsNjgsOTUsNDgsNDk=');
console.log('\''+x.replace(new RegExp(',', 'g'), '\',\'')+'\'');
console.log(String.fromCharCode('\'' + x.replace(new RegExp(',', 'g'), '\',\'') + '\''));

Now this would evaluate to

'80','65','83','83','87','79','82','68','95','48','49'

which is a correct parameter chain for String.fromCharCode()
because this works:

console.log(String.fromCharCode('80','65','83','83','87','79','82','68','95','48','49'));

Why doesn't it accept the variable as parameter?

Have I done something wrong here?

4

2 回答 2

2

在:

var x = atob('ODAsNjUsODMsODMsODcsNzksODIsNjgsOTUsNDgsNDk=');
console.log(String.fromCharCode('\'' + x.replace(new RegExp(',', 'g'), '\',\'') + '\''));

'\''+x.replace(new RegExp(',', 'g'), '\',\'')+'\''产生一个字符串。这只是一个文字说'80','65','83','83','87','79','82','68','95','48','49'。如果您将此字符串传递给String.fromCharCode... 绝对不是您想要的。JavaScript 应该如何将其转换为一个数字?

String.fromCharCode('80','65','83','83','87','79','82','68','95','48','49')

在这里,您传递了多个参数。多个字符串。它们中的每一个都可以很容易地转换成一个数字。

您可以做的就是简单地拆分字符串,,然后将结果数组分解:(ECMAScript 6)

String.fromCharCode(...x.split(','));
于 2016-12-12T12:49:56.243 回答
1

你可以只传递一个数组:

String.fromCharCode.apply(null, ['80','65','83','83','87','79','82','68','95','48','49'])

这是一个类似的..同样的问题:

我可以将数组传递给 fromCharCode

于 2016-12-12T12:51:06.123 回答