如何在 JavaScript 中將對象推送到數組
在 JavaScript 中將對象推送到數組:
- 使用
Array.push()
方法。 - 將一個或多個對像作為參數傳遞。
- 此方法在數組末尾添加一個或多個元素並返回新長度。
const users = []
const obj = {
name: 'John Doe',
age: 23
}
users.push(obj)
console.log(users)
// [ { name: 'John Doe', age: 23 } ]
您還可以將多個對像作為參數傳遞給 Array.push()
將多個對象添加到數組中的方法,如下所示:
const users = []
const obj1 = { name: 'John Doe', age: 23 }
const obj2 = { name: 'Jane Doe', age: 31 }
const obj3 = { name: 'Alex Lee', age: 18 }
users.push(obj1, obj2, obj3)
console.log(users)
// [
// { name: 'John Doe', age: 23 },
// { name: 'Jane Doe', age: 31 },
// { name: 'Alex Lee', age: 18 }
// ]
閱讀這篇文章,了解更多關於 JavaScript 數組以及如何將多條信息存儲到單個變量中的信息。