![](/img/trans.png)
[英]javascript - how to get object name or associative array index name?
[英]javascript: how to get index of an object in an associative array?
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 函數將第一個參數作為索引,索引必須是整數。
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;
})
返回包含給定值的鍵數組。
如果你不使用 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
,您可以更改函數的名稱,並記住不要聲明任何名為“未定義”的變量。
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;
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.