JavaScript:如何引用数组内部对象内的数组并向其推送内容?

时间:2018-03-13 19:56:39

标签: javascript arrays object reference push

我有以下数组:

var ships = [ { locations: [], hits:0 },
              { different: [], different1:0 },
              { different3: [], different2:0 } ];

如何引用阵列"位置"在第一个物体内并推动它的东西?谢谢!

2 个答案:

答案 0 :(得分:1)

您可以使用索引访问或解构分配

索引访问

var ships = [ { locations: [], hits:0 },
              { different: [], different1:0 },
              { different3: [], different2:0 } ];
              
ships[0].locations.push("Ele from SO");

console.log(ships)

解构分配

var ships = [ { locations: [], hits:0 },
              { different: [], different1:0 },
              { different3: [], different2:0 } ];
              
var [obj] = ships;
obj.locations.push("Ele from SO");

console.log(ships)

答案 1 :(得分:0)

应该是

ships[0].locations.push(newItem);