簡體   English   中英

返回數組鍵的關於其中一個包含對象的值的最佳方法

[英]Best way to return the key of an array about the value of one of its containing objects

我想知道實現這一共同行動的更好方法是什么:

var id = 1;
var Players = [{ id: 0, other: '...'}, { id: 1, other: '...' }]

for (var i=0; i<Players.length; i++) {
  if (Players[i].id == id) {
    return i;
  } 
}

我在考慮Array.map,但我不知道我們是否可以訪問密鑰:

Players.map(function(Player) { if (Player.id == id) { return ?? } });

取決於您的結構(並牢記性能); 使它成為一個關聯對象/數組可以解決。

var object = { id: 1, other: '...' };

var Players = [];
Players[object.id] = object;

然后,您可以通過以下方式引用ID所需的播放器:

var id = 1;
var playerObject = Players[id];

請注意,在這種情況下,您不能對ID使用負值或零值。

您也可以嘗試減少

// The second argument is set to null so that reduce doesn't just
// start with the first object in the array
Players.reduce(function(memo, Player, key) {
    return Player.id === id ? key : memo;
}, null);

Array.map()將索引作為第二個參數傳遞給回調。
但是,它無法幫助您找到單個項目。

Javascript數組沒有執行此操作的函數。

使用LoDash ,您可以非常輕松地執行此操作:

_.findIndex(Players, { id: 4 })

暫無
暫無

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

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