Most efficient way to prepend a value to an array

后端 未结 9 1133
予麋鹿
予麋鹿 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: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]
    

提交回复
热议问题