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

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

问题描述

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

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

推荐答案

使用 push() 函数追加到数组:

Use the push() function to append to an array:

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

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

console.log(arr);

将打印

["Hi", "Hello", "Bonjour", "Hola"]






您可以使用 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]);
}

将打印

Hi
Hello
Bonjour
Hola 
Salut
Hey






更新

如果如果要将一个数组的项添加到另一个数组,可以使用 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);

将打印

["apple", "banana", "cherry", "dragonfruit", "elderberry", "fig"]

更新

如果您想将任何值附加到某个开头,请添加此答案数组意味着第一个索引然后你可以使用用于此目的的unshift()

Just an addition to this answer if you want to append any value to the start of an array that means to the first index then you can use unshift() for this purpose.

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

将打印:

[0, 1, 2, 3]

它还支持多个值附加,就像push()方法一样。

It also supports multiple values appending just like push() method.

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

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