2013-03-13 140 views
0
var x = String.fromCharCode(65); 

console.log(x); //returns "A" 

它接受一個整數並返回相應的字符(字符串),但該字符的代碼完全等於輸入!String.fromCharCode()如何實現?

這裏發生了什麼?它真的只是返回它接受的內容嗎?還是有任何額外的邏輯?

+1

您可以查看規範:http://es5.github.com/#x15.5.3.2。 – 2013-03-13 19:38:32

回答

0

我相信這只是維持的ASCII碼字典和返回字符{}值輸入整數{}鍵

0

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 
    } 
} 
+0

謝謝!我知道它做了什麼!我對它是如何實現感興趣的...(在JS解釋器中) – DrStrangeLove 2013-03-13 19:23:02

2

看看@spidermonkey源代碼

fromCharCode在jsstr.cpp

定義它使用一個unitStringTable用於映射。該表是通過預處理器指令定義的...