簡體   English   中英

Javascript 轉義 (\\x) + 變量,

[英]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 ,它確實聽起來像。

  • 將 51₁₆ 傳遞給String.fromCharCode而不是 51₁₀
  • 51₁₆ 等於 81₁₀
  • 以下任何一種都可用於轉換
    • (81).toString(16)
    • 81..toString(16)
    • 81.0.toString(16)
    • numberVar.toString(16)

在閱讀了這個問題的答案和評論后,隨后進行了調查。

牢記我從問題中得出的假設

為什么主要的解決方案,即String.fromCharCode ,在嘗試時似乎沒有回答提問者的問題。

假設是問題在於傳遞給String.fromCharCode的參數類型。

下面在節點 repl 中演示了為什么'\\x51' === 'Q'返回trueString.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM