javascript:如何在关联数组中获取对象的索引?

gmu*_*mad 26 javascript

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);   
Run Code Online (Sandbox Code Playgroud)

上面的程序打印索引:-1,为什么?有没有更好的方法在不使用循环的情况下获取关联数组中对象的索引?

如果我想从这个数组中删除'key3'怎么办?splice函数将第一个参数作为索引,该索引必须是整数.

geo*_*org 39

indexOf仅适用于纯Javascript数组,即具有整数索引的数组.你的"数组"实际上是一个对象,应该这样声明

var associativeArray = {}
Run Code Online (Sandbox Code Playgroud)

对象没有内置的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);
}
Run Code Online (Sandbox Code Playgroud)

没有循环(假设现代浏览器):

foundKeys = Object.keys(associativeArray).filter(function(key) {
    return associativeArray[key] == value;
})
Run Code Online (Sandbox Code Playgroud)

返回包含给定值的键数组.

  • thg435:你可能在变量名中使用了'array'这个词,引起了一些混乱.或许`associativeMap`可能更好地说明它是一个对象,而不是一个数组? (3认同)
  • @gmuhammad`splice()`方法只对数组而不是对象进行操作.例如,您需要使用`delete associativeArray ['key3']`删除该属性. (2认同)