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

时间:2012-02-14 07:23:51

标签: 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);   

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

如果我想删除' key3'从这个阵列? splice函数将第一个参数作为索引,该参数必须是整数。

3 个答案:

答案 0 :(得分:38)

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 :(得分:2)

如果你不使用jQuery,你可以扩展Object的原型:

// 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;
    }
});

如果您使用jQuery,则使用这种方式而不是公共Object.prototype.associativeIndexOf = ...将使用它。

然后你可以像这样使用它:

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,你可以更改函数的名称,并且记住不要声明任何名为'undefined'的变量。

答案 2 :(得分:0)

let elementIndex = -1;

array.forEach((element, index, array) => {
   if (element["key"] == "someValue") {
      elementIndex = index;
   }
});

打字稿风格:

let elementIndex = -1;

this.array.forEach((element, index, array) => {
   if (element.key. == "someValue") {
      elementIndex = index;
   }
});
相关问题