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


当前回答

你.push()中的值。示例:array.push(value);

其他回答

您可以使用JavaScript Spread运算符语法:

// Initialize the array

var arr = [
    "Hi",
    "Hello",
    "Bangladesh"
];

// Append a new value to the array

arr = [...arr, "Feni"]; 

// Or you can add a variable value

var testValue = "Cool";

arr = [...arr, testValue ];

console.log(arr);

// Final output [ 'Hi', 'Hello', 'Bangladesh', 'Feni', 'Cool' ]

附加单个元素

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

如果arr是数组,而val是要添加的值,请使用:

arr.push(val);

E.g.

var arr=[‘a’,‘b’,‘c’];arr.push('d');控制台日志(arr);

一些快速基准测试(每个测试=500k附加元素,结果是多次运行的平均值)显示如下:

Firefox 3.6(Mac):

小型阵列:arr[arr.length]=b更快(300ms vs.800ms)大型阵列:arr.push(b)更快(500ms vs.900ms)

Safari 5.0(Mac):

小型阵列:arr[arr.length]=b更快(90ms比115ms)大型阵列:arr[arr.length]=b更快(160ms比185ms)

谷歌Chrome 6.0(Mac):

小阵列:没有显著差异(而且Chrome速度很快!只有~38ms!!)大型阵列:无显著差异(160ms)

我更喜欢arr.push()语法,但我认为我最好使用arr[arr.length]版本,至少在原始速度上。我很想看看IE运行的结果。


我的基准测试循环:

function arrpush_small() {
    var arr1 = [];
    for (a = 0; a < 100; a++)
    {
        arr1 = [];
        for (i = 0; i < 5000; i++)
        {
            arr1.push('elem' + i);
        }
    }
}

function arrlen_small() {
    var arr2 = [];
    for (b = 0; b < 100; b++)
    {
        arr2 = [];
        for (j = 0; j < 5000; j++)
        {
            arr2[arr2.length] = 'elem' + j;
        }
    }
}


function arrpush_large() {
    var arr1 = [];
    for (i = 0; i < 500000; i++)
    {
        arr1.push('elem' + i);
    }
}

function arrlen_large() {
    var arr2 = [];
    for (j = 0; j < 500000; j++)
    {
        arr2[arr2.length] = 'elem' + j;
    }
}

我们在JavaScript中没有Array的append函数,但我们有push和unshift。假设您有以下阵列:

var arr = [1, 2, 3, 4, 5];

我们喜欢向这个数组附加一个值。我们可以执行arr.push(6),它将在数组末尾添加6:

arr.push(6); // Returns [1, 2, 3, 4, 5, 6];

我们还可以使用unshift,看看我们如何应用它:

arr.unshift(0); // Returns [0, 1, 2, 3, 4, 5];

它们是向数组添加或追加新值的主要函数。