簡體   English   中英

如何優雅地使對象從名稱到JavaScript數組的索引?

[英]How can I elegantly make an object from names to indices from a javascript array?

我想轉變

myArr = ["Abel","Bella","Corey"]

進入

myIndex = {"Abel": 1, "Bella":2, "Corey":3}

(我知道我可以做.indexOf但我想做一個有效的查詢字典)

天真地我會這樣:

myIndex = {}
for(var i = 0; i < myArr.length; i++){myIndex[myArr[i]] = i;}

但是我覺得我應該可以用地圖做到這一點。 我可以通過地圖以某種方式傳遞索引嗎?

我不認為Array.map()在這里適合,因為map返回一個數組,可以使用Array.forEach()

var myArr = ["Abel", "Bella", "Corey"];
var obj = {};
myArr.forEach(function (val, idx) {
    obj[val] = idx;
})
console.log(obj)

.map()處理程序將把項目indx作為第二個參數

myArr.map(function (val, idx) {
    console.log(val, idx)
})

演示: 小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM