【问题标题】:JavaScript: How to reference an array inside an object inside an array and push something to it?JavaScript:如何在数组内的对象内引用数组并将某些内容推送给它?
【发布时间】:2018-03-13 19:56:38
【问题描述】:

我有以下数组:

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

如何引用第一个对象内的数组“位置”并将某些内容推送给它?谢谢!

【问题讨论】:

标签: javascript arrays object reference push


【解决方案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)

【讨论】:

    【解决方案2】:

    应该是

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

    【讨论】:

    • 对原发帖者(和未来的读者)稍加解释总是会让你的答案变得更好
    猜你喜欢
    • 2022-11-25
    • 1970-01-01
    • 2021-12-04
    • 2017-09-26
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    • 2019-07-20
    • 2019-06-20
    相关资源
    最近更新 更多