2012-02-14 137 views
22
var associativeArray = []; 

associativeArray['key1'] = 'value1'; 
associativeArray['key2'] = 'value2'; 
associativeArray['key3'] = 'value3'; 
associativeArray['key4'] = 'value4'; 
associativeArray['key5'] = 'value5'; 

var key = null; 
for(key in associativeArray) 
{ 
    console.log("associativeArray[" + key + "]: " + associativeArray[key]);   
} 

key = 'key3'; 

var obj = associativeArray[key];   

// gives index = -1 in both cases why? 
var index = associativeArray.indexOf(obj); 
// var index = associativeArray.indexOf(key); 

console.log("obj: " + obj + ", index: " + index); 

上面的程序打印索引:-1,爲什麼?有沒有更好的方式來獲取關聯數組中的對象的索引而不使用循環?javascript:如何獲取關聯數組中的對象的索引?

如果我想從這個數組中刪除'key3'會怎麼樣?拼接函數將第一個參數作爲必須爲整數的索引。

+8

JavaScript中沒有關聯數組。 – Sarfraz 2012-02-14 07:24:57

+0

[在javascript對象中,獲取值的屬性的最佳方式是什麼?](http://stackoverflow.com/questions/9052888/in-a-javascript-object-whats-best-way-to -get-the-attribute-of-value) – user123444555621 2012-02-14 07:27:33

+0

http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/ – 2012-02-14 07:35:10

回答

34

indexOf只適用於純Javascript數組,即具有整數索引的數組。您的「數組」實際上是一個對象,應宣佈爲

var associativeArray = {} 

有沒有內置的indexOf的對象,但它很容易寫。

var associativeArray = {} 

associativeArray['key1'] = 'value1'; 
associativeArray['key2'] = 'value2'; 
associativeArray['key3'] = 'value3'; 
associativeArray['key4'] = 'value4'; 
associativeArray['key5'] = 'value5'; 

var value = 'value3'; 
for(var key in associativeArray) 
{ 
    if(associativeArray[key]==value) 
     console.log(key); 
} 

沒有循環(假設一個現代瀏覽器):

foundKeys = Object.keys(associativeArray).filter(function(key) { 
    return associativeArray[key] == value; 
}) 

返回包含所述給定值的密鑰的陣列。

+1

如果我想從此刪除'key3'會怎麼樣陣列?拼接函數將第一個參數作爲必須爲整數的索引。 – gmuhammad 2012-02-14 07:41:06

+2

@gmuhammad'splice()'方法只對數組操作,而不是對象。例如,您需要使用delete associativeArray ['key3']'來刪除該屬性。 – GregL 2012-02-14 07:48:11

+3

thg435:通過在變量名中使用單詞「數組」,可能會引起一些混淆。也許'associativeMap'可能會更好地表明它是一個對象,而不是一個數組? – GregL 2012-02-14 07:49:35

2

如果你不使用jQuery,你可以繼承對象的這樣的原型:

// Returns the index of the value if it exists, or undefined if not 
Object.defineProperty(Object.prototype, "associativeIndexOf", { 
    value: function(value) { 
     for (var key in this) if (this[key] == value) return key; 
     return undefined; 
    } 
}); 

使用這種方式,而不是常見的Object.prototype.associativeIndexOf = ...將與jQuery的工作,如果你使用它。

然後你可以使用這樣的:

var myArray = {...}; 
var index = myArray.associativeIndexOf(value); 

它也將與正常工作數組:[...],所以你可以用它來代替indexOf了。

記得使用三字符運營商,以檢查它是否未定義:

index === undefined // to check the value/index exists  
index !== undefined // to check the value/index does not exist 

當然,如果你喜歡,例如keyOf你可以改變函數的名字,記得不要聲明任何變量稱爲'未定義'。

相關問題