Most efficient way to prepend a value to an array

后端 未结 9 997
予麋鹿
予麋鹿 2020-12-02 04:53

Assuming I have an array that has a size of N (where N > 0), is there a more efficient way of prepending to the array that would not require O(N

相关标签:
9条回答
  • 2020-12-02 05:19

    Example of prepending in-place:

    var A = [7,8,9]
    var B = [1,2,3]
    
    A.unshift(...B)
    
    console.log(A) // [1,2,3,7,8,9]

    0 讨论(0)
  • 2020-12-02 05:20

    f you need to preserve the old array, slice the old one and unshift the new value(s) to the beginning of the slice.

    var oldA=[4,5,6];
    newA=oldA.slice(0);
    newA.unshift(1,2,3)
    
    oldA+'\n'+newA
    
    /*  returned value:
    4,5,6
    1,2,3,4,5,6
    */
    
    0 讨论(0)
  • 2020-12-02 05:21

    There is special method:

    a.unshift(value);
    

    But if you want to prepend several elements to array it would be faster to use such a method:

    var a = [1, 2, 3],
        b = [4, 5];
    
    function prependArray(a, b) {
        var args = b;
        args.unshift(0);
        args.unshift(0);
        Array.prototype.splice.apply(a, args);
    }
    
    prependArray(a, b);
    console.log(a); // -> [4, 5, 1, 2, 3]
    
    0 讨论(0)
提交回复
热议问题