如何在Javascript中将对象推入数组

How to push an object into an array in Javascript

本文关键字:对象 数组 Javascript      更新时间:2023-09-26

我有一个包含对象的数组,我想给它添加一个新对象。

//here is my array    
var countries = [
    { start: 20.2, end: 20.7, country_name: "United States" },
    { start: 20.7, end: 21.2, country_name: "Canada" }
]
//new object to push in this array    
{ start: 23.2, end: 23.7, country_name: "Peru" }

你看文档了吗?我希望你下次能先找找看。让我们远离这些琐碎的问题

countries.push({ start: 23.2, end: 23.7, country_name: "Peru" })

使用以下代码:

var newObj = { start: 23.2, end: 23.7, country_name: "Peru" }
countries.push(newObj);