繁体   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