2012-02-14 99 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你可以改变函数的名字,记得不要声明任何变量称为'未定义'。

相关问题