Xufoxsamccone提出了一个问题:Most efficient way to prepend a value to an array,或许与您遇到的问题类似。
回答者maerics给出了该问题的处理方式:
I'm not sure about more efficient in terms of big-O but certainly using the unshift
method is more concise:
--- - - --- -- -- --- ------------- -- -- -- --- -- -- -- --
[Edit]
This jsPerf benchmark shows that unshift
is decently faster in at least a couple of browsers, regardless of possibly different big-O performance iff you are ok with modifying the array in-place. 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:
--------------------- -- --- ------- -- ----- -------- ----
[Edit 2]
For completeness, the following function can be used instead of OP's example prependArray(...)
to take advantage of the Array unshift(...)
method:
-------- -------------- ------ - --- -------- - -------------- ------------------------ ------ --------- - --- - - --- -- --- --- - - ---------- --- -- -- -- --- -- -- --- -- -- -- --- -- ---
希望本文对你有帮助,欢迎支持JavaScript中文网
来源:JavaScript中文网 ,转载请注明来源 本文地址:https://www.javascriptcn.com/post/9108