[英]Javascript Escape (\x) + Variable,
一直在玩 Javascript 并发现似乎很有趣的转义 (\\x)。
为了澄清我刚刚发现我可以使用转义 + x 将两位数转换为一个字母,
像"\\x51"
输出是Q
一直在搜索这个特定主题,但不确定从哪里开始,因为我什至不知道他们叫它什么,就像我知道 PHP 和 Javascript 中的反斜杠目的,但我不知道它与x
结合时的作用
现在我的问题是,是否可以在 X 之后添加动态数值?
就像我试图创建一个这样的函数,但它似乎不可能,因为它看起来需要在x
之后有两个字符(数字或字母)。
function __num_string( num ) {
return "\x"+num;
}
期望__num_string( 51 )
将返回Q
现实Uncaught SyntaxError: Unexpected token ILLEGAL
如果可能的话,我将不胜感激,
谢谢
是的,这是可能的,但有一个更好的方法:
return String.fromCharCode(num);
... 其中num
是您想要获取的字符的 Unicode 值。
尽管如此,从技术上讲,使用eval
按照您最初预期的方式实现您的功能:
function __num_string( num ) {
if (/^[a-f0-9]{1,2}$/i.test(num)) {
return eval('"\\x' + num + '"');
}
}
注意区别: num
应该是一个表示十六进制值的字符串。
现在关于你得到的错误:这...
'\x'
... 是技术上无效的字符串。 解析字符串文字时,解析器期望序列\\x
后跟[0-9a-f]
字符范围。 然而,在你的情况下,那里没有类似的东西,因此Unexpected token ILLEGAL
。
字符串转义是一种语法特征,是字符串文字的一部分。
在运行时这样做是没有意义的。
您正在寻找String.fromCharCode
,它确实听起来像。
String.fromCharCode
而不是 51₁₀(81).toString(16)
81..toString(16)
81.0.toString(16)
numberVar.toString(16)
在阅读了这个问题的答案和评论后,随后进行了调查。
牢记我从问题中得出的假设
为什么主要的解决方案,即String.fromCharCode
,在尝试时似乎没有回答提问者的问题。
假设是问题在于传递给String.fromCharCode
的参数类型。
下面在节点 repl 中演示了为什么'\\x51' === 'Q'
返回true
而String.fromCharCode(51) === 3
也返回true
。
> 0x51 // es6 hexadecimal literal
81
> 0x51.toString(16) // Same as (81).toString(16)
'51'
> String.fromCharCode(0x51) // Same as String.fromCharCode(81)
'Q'
> (81).toString(16) // Same as 0x51.toString(16)
51
> String.fromCharCode(81) // Same as String.fromCharCode(0x51)
'Q'
> 0x33 // es6 hexadecimal literal
51
> 0x33.toString(16) // literal to base 16 string
'33'
> String.fromCharCode(0x33)
'3'
> String.fromCharCode(51)
'3'
如果您想自己尝试,只需陈述。
0x51
0x51.toString(16)
String.fromCharCode(0x51)
(81).toString(16)
String.fromCharCode(81)
0x33
0x33.toString(16)
String.fromCharCode(0x33)
String.fromCharCode(51)
似乎所讨论的方法采用十六进制字符串。
如果它是一个数字,则隐式调用以 16 作为基数传递的 toString()。
下面是一个进行转换的函数。
function toHex(n) {
if (typeof n === 'string') return `${parseInt(n, 16)}`;
return `0x${n}`;
}
它可以与数字一起使用
> String.fromCharCode(toHex(33))
'3'
> String.fromCharCode(toHex(51))
'Q'
它可以与字符串一起使用
> String.fromCharCode(toHex('33'))
'3'
> String.fromCharCode(toHex('51'))
'Q'
它可以与十六进制数字一起使用,但只能用作字符串...
> String.fromCharCode(toHex('3f'))
'?'
因为没有它,十六进制数字文字就可以了。
> String.fromCharCode(0x3f)
'?'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.