虽然我有一些基础的JavaScript背景,但我写下了以下代码:
var data=[{"_id":"57b3e7ec9b209674f1459f36","fName":"Tom","lName":"Moody","email":"Tom@example.com","age":30},{"_id":"57b3e8079b209674f1459f37","fName":"Pat","lName":"Smith","email":"pat@example.com","age":32},{"_id":"57b3e8209b209674f1459f38","fName":"Sam","lName":"Dawn","email":"sam@example.com","age":28},{"_id":"57b3e8219b209674f1459f39","fName":"Sam","lName":"Dawn","email":"sam@example.com","age":28}]
var tempArr=[];
var table=[];
var dataArr = Object.keys(data).map(function(k) { return data[k] });
dataArr.forEach(function(user) {
tempArr[0]=user.fName;
tempArr[1]=user.lName;
tempArr[2]=user.email;
tempArr[3]=user.age;
table.push(tempArr);
console.log('table'+JSON.stringify(table));
});
在最后一个循环中,我期望table包含Tom、Pat和Sam的数组。然而,实际情况是这样的:
table[["Tom","Moody","Tom@example.com",30]]
table[["Pat","Smith","pat@example.com",32],["Pat","Smith","pat@example.com",32]]
table[["Sam","Dawn","sam@example.com",28],["Sam","Dawn","sam@example.com",28],["Sam","Dawn","sam@example.com",28]]
table[["Sam","Dawn","sam@example.com",28],["Sam","Dawn","sam@example.com",28],["Sam","Dawn","sam@example.com",28],["Sam","Dawn","sam@example.com",28]]
为什么 push() 会替换表格中的先前条目?非常感谢您的帮助。