![](/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.