我的目標是創建一個這樣的數組:推對象轉換成數組作爲預期不起作用
[{"str":"a","number":1},{"str":"a","number":2},{"str":"b","number":1},{"str":"b","number":2}]
所以我寫了這個JavaScript
abc = ["a","b"]
num = [1,2]
arr = []
a = {}
for (var i in abc)
{
str = abc[i]
a.str = str;
for(var x in num)
{
number = num[x]
a.number = number
console.log(a)
arr.push(a)
}
}
控制檯日誌看起來不錯,但數組看起來像這樣:
[{"str":"b","number":2},{"str":"b","number":2},{"str":"b","number":2},{"str":"b","number":2}]
任何人都可以解釋這一點嗎?
這裏只有一個涉及對象;您的代碼會更新該對象並將其推入陣列中多次。如果您需要不同的對象,則必須在每次迭代時爲「a」創建一個新值。另外,用'var'或'let'聲明你的變量。 – Pointy