var x = String.fromCharCode(65);
console.log(x); //returns "A"
它接受一個整數並返回相應的字符(字符串),但該字符的代碼完全等於輸入!String.fromCharCode()如何實現?
這裏發生了什麼?它真的只是返回它接受的內容嗎?還是有任何額外的邏輯?
var x = String.fromCharCode(65);
console.log(x); //returns "A"
它接受一個整數並返回相應的字符(字符串),但該字符的代碼完全等於輸入!String.fromCharCode()如何實現?
這裏發生了什麼?它真的只是返回它接受的內容嗎?還是有任何額外的邏輯?
我相信這只是維持的ASCII碼字典和返回字符{}值輸入整數{}鍵
fromCharCode
用於將Unicode數字轉換成字符。 Unicode 65
是字符A
。所以String.fromCharCode(65)
返回A
。
What happens under the hood here?
實現方式可以是用HashMap
鍵 - 值對,其中的Unicode值被映射到對應的字符,或者可以是switch
聲明這需要Unicode
並返回character
。使用switch
實施
僞代碼:
function fromCharCode(*args)
{
return args.map(unicodeToChar).join('')
}
function unicodeTochar(unicode)
{
switch(unicode)
{
//something
case 65:
return 'A'
case 66:
return 'B'
//something
}
}
謝謝!我知道它做了什麼!我對它是如何實現感興趣的...(在JS解釋器中) – DrStrangeLove 2013-03-13 19:23:02
您可以查看規範:http://es5.github.com/#x15.5.3.2。 – 2013-03-13 19:38:32