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)
返回包含给定值的键数组.
| 归档时间: |
|
| 查看次数: |
75044 次 |
| 最近记录: |