示例 1: 使用 push() 将对象追加到数组
// program to append an object to an array function insertObject(arr, obj) { // append object arr.push(obj); console.log(arr); } // original array let array = [1, 2, 3]; // object to add let object = {x: 12, y: 8}; // call the function insertObject(array, object);
输出
[1, 2, 3, {x: 12, y: 8}]
在上面的程序中,
push()
方法用于向数组中添加一个对象。
push()
方法在数组末尾添加一个项。
示例 2: 使用 splice() 将对象附加到数组
// program to append an object to an array function insertObject(arr, obj) { // find the last index let index = arr.length; // appending object to end of array arr.splice(index, 0, object); console.log(arr); } // original array let array = [1, 2, 3]; // object to add let object = {x: 12, y: 8}; // call the function insertObject(array, object);
输出
[1, 2, 3, {x: 12, y: 8}]
在上面的程序中,
splice()
方法用于向数组中添加一个对象。
splice()
方法添加和/或删除项目。
在
第一个参数表示要插入项目的索引。
第二个参数表示要删除的项目数(此处为 0)。
第三个参数表示要添加到数组中的元素。
splice()
方法中,
示例 3: 使用扩展运算符追加对象
// program to append an object to an array function insertObject(arr, obj) { // append object arr = [...arr, object]; console.log(arr); } // original array let array = [1, 2, 3]; // object to add let object = {x: 12, y: 8}; // call the function insertObject(array, object);
输出
[1, 2, 3, {x: 12, y: 8}]
在上面的程序中,扩展运算符
...
用于将对象添加到数组中。
展开语法允许您将所有元素复制到数组中。然后,对象被添加到数组的末尾。