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


当前回答

使用凹面:

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

其他回答

使用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);

您可以使用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"]

在数组上追加项

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]);
}

附加单个元素

// 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(),例如arr.push(“测试1”、“测试2”);。

如果您有数组,可以使用concat(),例如Array1.contat(Array2)。

如果只有一个元素要添加,也可以尝试长度方法,例如array[aray.length]=“test”;。