I'm not sure about more efficient in terms of big-O but certainly using the unshift
method is more concise:(我不确定在big-O方面效率更高,但肯定使用unshift
方法更简洁:)
var a = [1, 2, 3, 4];
a.unshift(0);
a; // => [0, 1, 2, 3, 4]
[Edit]([编辑])
This jsPerf benchmark shows that unshift
is decently faster in at least a couple of browsers, regardless of possibly different big-O performance if you are ok with modifying the array in-place.(这jsPerf基准表明, unshift
是体面的至少几个浏览器速度更快,无论可能不同的大O性能,如果您没有问题修改就地数组。)
If you really can't mutate the original array then you would do something like the below snippet, which doesn't seem to be appreciably faster than your solution:(如果你真的无法改变原始数组,那么你会做类似下面的代码片段,它似乎没有比你的解决方案快得多:)
a.slice().unshift(0); // Use "slice" to avoid mutating "a".
[Edit 2]([编辑2])
For completeness, the following function can be used instead of OP's example prependArray(...)
to take advantage of the Array unshift(...)
method:(为了完整性,可以使用以下函数代替OP的示例prependArray(...)
来利用Array unshift(...)
方法:)
function prepend(value, array) {
var newArray = array.slice();
newArray.unshift(value);
return newArray;
}
var x = [1, 2, 3];
var y = prepend(0, x);
y; // => [0, 1, 2, 3];
x; // => [1, 2, 3];
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…