2015-04-29 39 views
1

我都接受,我想爲重點,以對象使用函數參數的函數...使用函數作爲對象的關鍵

function foo(func) { 
    return { func: true }; 
} 

這當然,返回一個對象與字符串'func'作爲關鍵(不是我想要的)。

正確的解決方案是從func創建一個字符串,然後創建對象?

有沒有辦法從一個函數創建一個散列?

+2

你想實現什麼功能? /你不能使用函數_name_作爲鍵...? – fast

+2

對象中的鍵總是字符串或數字。在這裏你可以閱讀更多:http://stackoverflow.com/questions/6066846/keys-in-javascript-objects-can-only-be-strings – vjdhama

回答

0

銘記object keys are always strings你應該能夠使用這個語法:

result = {}; 
result[func] = true; 
return result; 
+0

做到了。謝謝@ D方! – sfletche

+1

@sfletche當然。但要小心:鍵總是字符串。即使其他類型可能乍看起來工作,他們可能會咬你以後的尷尬的錯誤。 –

0

雖然你可以直接使用功能鍵,您可以使用的哈希碼函數來獲取函數的字符串表示創建整數鍵。我從http://erlycoder.com/49/javascript-hash-functions-to-convert-string-into-integer-hash-得到一個。

function hashFunc(func){ 
    var str = func.toString(); 

    var hash = 0; 
    if (str.length == 0) return hash; 
    for (i = 0; i < str.length; i++) { 
     char = str.charCodeAt(i); 
     hash = ((hash<<5)-hash)+char; 
     hash = hash & hash; // Convert to 32bit integer 
    } 
    console.log(hash); 
    return hash; 
} 

var col = {} 

function add(func) { 
    col[hashFunc(func)] = true; 
} 

function get(func) { 
    return col[hashFunc(func)] || false; 
} 

// test 
add(hashFunc); 
console.log(get(add)); // false 
console.log(get(hashFunc)); // true 
相關問題