如何在JavaScript中将对象(如字符串或数字)附加到数组中?


当前回答

使用凹面:

a=[1,2,3];b=[3,4,5];a=混凝土(b);控制台日志(a);

其他回答

现在大多数浏览器都支持ECMAScript 5(ES5)标准的JavaScript,您可以使用apply()将array1附加到array2。

var array1 = [3, 4, 5];
var array2 = [1, 2];

Array.prototype.push.apply(array2, array1);

console.log(array2); // [1, 2, 3, 4, 5]

带有ECMAScript 6(ES6)标准的JavaScript,Chrome、Firefox、Internet Explorer和Edge支持该标准,您可以使用扩展运算符:

"use strict";
let array1 = [3, 4, 5];
let array2 = [1, 2];

array2.push(...array1);

console.log(array2); // [1, 2, 3, 4, 5]

排列运算符将替换array2.push(…array1);带有阵列2.推(3,4,5);当浏览器思考逻辑时。

加分

如果要创建另一个变量来存储两个数组中的所有项,可以执行以下操作:

ES5 var combinedArray=array1.concat(array2);

ES6常量组合数组=[…array1,…array2]

扩展运算符(…)用于扩展集合中的所有项目。

如果要附加两个数组-

var a = ['a', 'b'];
var b = ['c', 'd'];

那么您可以使用:

var c = a.concat(b);

如果您想将记录g添加到数组(var a=[]),那么可以使用:

a.push('g');

附加单个元素

// Append to the end
arrName.push('newName1');

// Prepend to the start
arrName.unshift('newName1');

// Insert at index 1
arrName.splice(1, 0,'newName1');
// 1: index number, 0: number of element to remove, newName1: new element


// Replace index 3 (of exists), add new element otherwise.
arrName[3] = 'newName1';

附加多个元素

// Insert from index number 1
arrName.splice(1, 0,'newElemenet1', 'newElemenet2', 'newElemenet3');
// 1: index number from where insert starts,
// 0: number of element to remove,
//newElemenet1,2,3: new elements

附加一个数组

// Join two or more arrays
arrName.concat(newAry1, newAry2);
//newAry1,newAry2: Two different arrays which are to be combined (concatenated) to an existing array

您可以使用push方法。

Array.prototype.append = function(destArray){
    destArray = destArray || [];
    this.push.call(this, ...destArray);
    return this;
}
var arr = [1,2,5,67];
var arr1 = [7,4,7,8];
console.log(arr.append(arr1)); // [7, 4, 7, 8, 1, 4, 5, 67, 7]
console.log(arr.append("Hola")) // [1, 2, 5, 67, 7, 4, 7, 8, "H", "o", "l", "a"]

将值附加到数组

由于Array.prototype.push将一个或多个元素添加到数组的末尾,并返回数组的新长度,因此有时我们只想获得最新的数组,这样我们就可以这样做:

const arr = [1, 2, 3];
const val = 4;

arr.concat([val]); // [1, 2, 3, 4]

或者只是:

[...arr, val] // [1, 2, 3, 4]