這個問題在這里已經有了答案: 如何從多個陣列創建物件陣列 2 個答案 7 小時前關閉。
我有兩個清單,
l1= ["apple","banana","grape"]
l2 = ["red","yellow","black"]
如何制作這種型別的串列?(物件串列)
l3 = [
{fruit:"apple",colour:"red"},
{fruit:"banana",colour:"yellow"},
{fruit:"grape",colour:"balack"}
]
我嘗試了這樣的事情,但輸出不是我所期望的:
let l3 = [];
let Obj = {};
for (let l = 0;l<l1.length;l ) {
Obj = {};
for (h=0;h<l2.length;h ) {
Obj["fruit"] = l1[h];
Obj["colour"] = l2[h];
}
l3.push(Obj);
}
return l3;
uj5u.com熱心網友回復:
您只需要一個回圈,而不是嵌套回圈。
for (let i = 0; i < l1.length; i ) {
l3.push({fruit: l1[i], colour: l2[i]});
}
uj5u.com熱心網友回復:
您可以使用.map.
const l1 = ["apple", "banana", "grape"];
const l2 = ["red", "yellow", "black"];
const l3 = l1.map((fruit, index) => ({ fruit, color: l2[index] }));
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/427828.html
標籤:javascript 数组
上一篇:上傳后在div中顯示img
