How to append something to an array?

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


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

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

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

console.log(arr);

If you're only appending a single variable, then push() works just fine. If you need to append another array, use concat() :

var ar1 = [1, 2, 3];
var ar2 = [4, 5, 6];

var ar3 = ar1.concat(ar2);

alert(ar1);
alert(ar2);
alert(ar3);

Will spit out:

"1,2,3"
"4,5,6"
"1,2,3,4,5,6"

The concat does not affect ar1 and ar2 unless reassigned, for example:

ar1 = ar1.concat(ar2);
alert(ar1);

Will display:

"1,2,3,4,5,6"

Lots of great info here


Some quick benchmarking (each test = 500k appended elements and the results are averages of multiple runs) showed the following:

Firefox 3.6 (Mac):

  • Small arrays: arr[arr.length] = b is faster (300ms vs. 800ms)
  • Large arrays: arr.push(b) is faster (500ms vs. 900ms)
  • Safari 5.0 (Mac):

  • Small arrays: arr[arr.length] = b is faster (90ms vs. 115ms)
  • Large arrays: arr[arr.length] = b is faster (160ms vs. 185ms)
  • Google Chrome 6.0 (Mac):

  • Small arrays: No significant difference (and Chrome is FAST! Only ~38ms !!)
  • Large arrays: No significant difference (160ms)
  • I like the arr.push() syntax better, but I think I'd be better off with the arr[arr.length] Version, at least in raw speed. I'd love to see the results of an IE run though.


    My benchmarking loops:

    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;
        }
    }
    
    链接地址: http://www.djcxy.com/p/376.html

    上一篇: 迭代HashMap

    下一篇: 如何将某些东西附加到数组中?