示例 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, 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}]
在上面的程序中,splice()
方法用于将对象添加到数组中。
splice()
方法添加和/或删除一项。
在 splice()
方法中,
- 第一个参数表示要插入项的索引。
- 第二个参数表示要删除的项数 (此处为 0)。
- 第三个参数表示要添加到数组的元素。
示例 3:使用展开运算符附加对象
// program to append an object to an array
function insertObject(arr, obj) {
// append object
arr = [...arr, 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}]
在上面的程序中,展开运算符 ...
用于将对象添加到数组中。
展开语法允许您将所有元素复制到一个数组中。然后,将对象添加到数组的末尾。
另请阅读