javascript:如何在关联数组中获取对象的索引? [英] javascript: how to get index of an object in an associative array?

查看:83
本文介绍了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,为什么?有没有更好的方法在不使用循环的情况下获取关联数组中对象的索引?


The above program prints index: -1, why? Is there any better way to get index of an object in an associative array without using loops?

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

What if I want to delete 'key3' from this array? the splice function takes first parameter as index which must be an integer.

推荐答案

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

indexOf only works with pure Javascript arrays, i.e. those with integer indexes. Your "array" is actually an object and should be declared as such

var associativeArray = {}

对象没有内置的indexOf,但写起来很容易。

There's no built-in indexOf for objects, but it's easy to write.

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

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

Without loops (assuming a modern browser):

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

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

returns an array of keys that contain the given value.

这篇关于javascript:如何在关联数组中获取对象的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆