![](/img/trans.png)
[英]How can I add image source file info into a new array inside of another array in javascript
[英]How can I add an array into another array in Javascript?
我有一个两个元素的数组看起来像这样
headers = [{x: 1, y: 2},{x: 2, y: 3}]
我还有另一个三元素数组,如下所示:
ans = [{r: true},{r: false},{r:true}]
如何将第二个数组添加到第一个数组的第一行中以给出:
[{x: 1, y: 2, ans: [{r: true},{r: false},{r:true}] },{x: 2, y: 3}]
请注意,我不想预先定义ans,因为它可能是数组或其他东西。 也很抱歉,但我认为我对数组的表示可能不是正确的语法。 希望有道理。
您实际上想将另一个属性添加到数组中的元素。 你可以这样
headers[0].ans = ans;
只需将属性分配给对象: headers[0].ans = ans
你可以做这样的事情...
var headers = [{x: 1, y: 2},{x: 2, y: 3}];
var ans = [{r: true},{r: false},{r:true}];
// define what you want the newly added property to be called
var collectionName = "ans";
// assign it only to the first item in the headers array
headers[0][collectionName] = ans;
// here are your results
console.log(JSON.stringify(headers));
这是一个工作的小提琴,它将输出数组供您在输出div中查看
var headers = [{x: 1, y: 2},{x: 2, y: 3}],
ans = [{r: true},{r: false},{r:true}];
headers[0].ans = ans;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.