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


当前回答

现在大多数浏览器都支持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]

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

其他回答

附加单个元素

// 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

使用Array.prototype.push方法将值附加到数组末尾:

//初始化数组变量arr=[“嗨”,“你好”,“你好”];//将新值附加到数组arr.push(“Hola”);控制台日志(arr);


您可以使用push()函数在一次调用中将多个值附加到数组中:

//初始化数组var arr=[“Hi”,“你好”,“Bonjour”,“Hola”];//将多个值附加到数组arr.push(“Salut”,“嘿”);//显示所有值对于(变量i=0;i<arr.length;i++){控制台日志(arr[i]);}


使现代化

如果要将一个数组的项添加到另一个数组,可以使用firstArray.concat(secondArray):

变量arr=[“苹果”,“香蕉”,“樱桃”];//不要忘记分配结果,因为与push不同,concat不会更改现有数组arr=arr.concat([“龙果”,“接骨木”,“无花果”]);控制台日志(arr);

使现代化

如果你想在数组的开头加上任何值(即第一个索引),那么你可以使用array.prototype.unshift。

var arr=[1,2,3];arr.unshift(0);控制台日志(arr);

它还支持像push一样一次附加多个值。


使现代化

ES6语法的另一种方法是使用扩展语法返回新数组。这使原始数组保持不变,但返回一个附加了新项的新数组,符合函数式编程的精神。

常量arr=[“嗨”,“你好”,“你好”,];常量newArr=[…arr,“致敬”,];console.log(newArr);

在数组上追加项

let fruits = ["orange", "banana", "apple", "lemon"]; /* Array declaration */

fruits.push("avacado"); /* Adding an element to the array */

/* Displaying elements of the array */

for(var i=0; i < fruits.length; i++){
  console.log(fruits[i]);
}

当然,concat()也可以用于二维数组。无需循环。

var a = [
    [1, 2],
    [3, 4] ];

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

b = b.concat(a);

alert(b[2][1]); // Result: 2

如果要将单个值附加到数组中,只需使用push方法。它将在数组末尾添加一个新元素。

但是,如果您打算添加多个元素,请将这些元素存储在一个新数组中,并将第二个数组与第一个数组连接起来。。。无论你想怎样。

arr=['a','b','c'];
arr.push('d');
//now print the array in console.log and it will contain 'a','b','c','d' as elements.
console.log(array);