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

33
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函数的第一个参数必须是一个整数索引。


10
JavaScript 中没有关联数组。 - Sarfraz
1
可能是重复的问题:在JavaScript对象中,获取值的属性的最佳方法是什么? - user123444555621
http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/ - Billy Moon
3个回答

42

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”怎么办?splice函数的第一个参数必须是整数类型的索引。 - gmuhammad
2
@gmuhammad splice() 方法只能用于数组,而不能用于对象。你需要使用 delete associativeArray['key3'] 来删除属性,例如。 - GregL
4
你可能因在变量名中使用了“array”一词而引起了一些困惑。也许使用associativeMap会更好,以明确它是一个对象而不是数组? - GregL
1
@thg435 和 GregL:非常感谢你们两个,GregL,你是对的,我很困惑,希望这个数组被视为传统数组。但现在我已经清楚了。 :) - gmuhammad

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

使用这种方式而不是常见的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,并记住不要声明任何名为“undefined”的变量。

1
let elementIndex = -1;

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

TypeScript风格:

let elementIndex = -1;

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接