2012-06-07 100 views
5

嗨的關鍵我目前獲取的陣列。每個獲取關聯數組

$.each(messages, function(key,message){ doStuff(); }); 

但關鍵是數組的索引,而不是關聯鍵。

我怎樣才能很容易地得到它?

感謝

+5

一個數組沒有任何關聯鍵。索引是關鍵。你想做什麼? – Guffa

+2

你在哪裏Array即'messages'?發佈 – thecodeparadox

+1

您能否提供一個示例數組(2-3個元素)以及您期望的「關聯密鑰」? –

回答

9
var data = { 
    val1 : 'text1', 
    val2 : 'text2', 
    val3 : 'text3' 
}; 
$.each(data, function(key, value) { 
    alert("The key is '" + key + "' and the value is '" + value + "'"); 
}); 
​ 

Demo

+0

謝謝,我將使用一個數組來獲得這項工作,你是對的 –

0

JavaScript沒有 「關聯數組」,如PHP,但對象。但是,對象可能具有對應於某個值的字符串鍵。數組是數值列表,因此,如果key是一個數字,它必須是您正在使用的數組而不是對象,因此您無法獲得密鑰,因爲沒有數據。

因此,您可能想要使用簡單的for -loop代替基於回調的迭代器(如$.each)遍歷數組。

19

JavaScript沒有「關聯數組」。它有數組:

[1, 2, 3, 4, 5] 

和對象:

{a: 1, b: 2, c: 3, d: 4, e: 5} 

Array的沒有 「鑰匙」,他們有指標,其計數從0開始。

陣列使用[]訪問,並且可以使用[].訪問對象。

例子:

var array = [1,2,3]; 
array[1] = 4; 
console.log(array); // [1,4,3] 

var obj = {}; 
obj.test = 16; 
obj['123'] = 24; 
console.log(obj); // {test: 16, 123: 24} 

如果您嘗試訪問使用字符串作爲密鑰,而不是一個int,可能導致的一系列問題。您將設置數組的屬性而不是值。

var array = [1,2,3]; 
array['test'] = 4; // this doesn't set a value in the array 
console.log(array); // [1,2,3] 
console.log(array.test); // 4 

jQuery的$.each適用於這兩者。在$.each的回調中,第一個參數key是對象的鍵或數組的索引。

$.each([1, 2, 3, 4, 5], function(key, value){ 
    console.log(key); // logs 0 1 2 3 4 
}); 

$.each({a: 1, b: 2, c: 3, d: 4, e: 5}, function(key, value){ 
    console.log(key); // logs 'a' 'b' 'c' 'd' 'e' 
});