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


当前回答

push()将一个新元素添加到数组的末尾。

pop()从数组末尾删除元素。

要将对象(如字符串或数字)附加到数组,请使用:

array.push(toAppend);

其他回答

附加单个元素

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

如果要附加两个数组-

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

那么您可以使用:

var c = a.concat(b);

如果您想将记录g添加到数组(var a=[]),那么可以使用:

a.push('g');

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

一些快速基准测试(每个测试=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;
    }
}

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