如何将某些内容附加到数组? [英] How to append something to an array?

查看:26
本文介绍了如何将某些内容附加到数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I append an object (such as a string or number) to an array in JavaScript?

推荐答案

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

Use the Array.prototype.push method to append values to the end of an array:

// initialize array
var arr = [
  "Hi",
  "Hello",
  "Bonjour"
];

// append new value to the array
arr.push("Hola");

console.log(arr);

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

You can use the push() function to append more than one value to an array in a single call:

// initialize array
var arr = ["Hi", "Hello", "Bonjour", "Hola"];

// append multiple values to the array
arr.push("Salut", "Hey");

// display all values
for (var i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

更新

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

If you want to add the items of one array to another array, you can use firstArray.concat(secondArray):

var arr = [
  "apple",
  "banana",
  "cherry"
];

arr = arr.concat([
  "dragonfruit",
  "elderberry",
  "fig"
]);

console.log(arr);

更新

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

Just an addition to this answer if you want to prepend any value to the start of an array (i.e. first index) then you can use Array.prototype.unshift for this purpose.

var arr = [1, 2, 3];
arr.unshift(0);
console.log(arr);

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

It also supports appending multiple values at once just like push.

更新

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

Another way with ES6 syntax is to return a new array with the spread syntax. This leaves the original array unchanged, but returns a new array with new items appended, compliant with the spirit of functional programming.

const arr = [
  "Hi",
  "Hello",
  "Bonjour",
];

const newArr = [
  ...arr,
  "Salut",
];

console.log(newArr);

这篇关于如何将某些内容附加到数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆