簡體   English   中英

JavaScript使用索引更新數組元素

[英]JavaScript updating an array element with index

我現在有一個arrayList()稱為players在JavaScript中,我push使用的數據到它: players.push({name: msg.name, map: msg.map, coords: msg.coords});

以下是一個示例數據: { name: 'weka', map: '5', coords: '12.4' } ,例如players[0]

這是我在做的事情:

for (var i = 0; i < players.length; ++i) {
  if (msg.name === players[i].name) {
    console.log("Updating  index ("+i+") player: " + msg.name);
    //players[i].push({name: msg.name, map: msg.map, coords: msg.coords});
  }
}
players[i].push({name: msg.name, map: msg.map, coords: msg.coords});

應該

players[i] = {name: msg.name, map: msg.map, coords: msg.coords});

你還沒有將players[i]定義為一個數組,所以沒有什么可以“推”到。 我認為你希望改變現有的價值,而不是插入額外的深度。

players.push({name: msg.name, map: msg.map, coords: msg.coords}); 沒關系,

你做的是players[i].push({name: msg.name, map: msg.map, coords: msg.coords}); players[i]不是陣列。

玩家[i] - 是對象( { name: 'weka', map: '5', coords: '12.4' } for example ),不是數組如果你想設置集合道具只需使用palyers[i]['prop'] = 'prop';

暫無
暫無

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

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