Javascript “shift” versus “splice” - are these statements equal?

后端 未结 3 656
孤城傲影
孤城傲影 2021-02-05 06:57

I just want to confirm if the following two Javascript statements produces the same results, as it seems to me:

First:

var element = my_array.splice(0,1)         


        
3条回答
  •  孤独总比滥情好
    2021-02-05 07:24

    They will have the same effect, yes. splice(0, 1) will remove the first element from my_array and return a new array containing that element. shift will do the same, but return the element itself, not an array.

    shift is more readable (in my opinion) and is also significantly faster (in Chrome at least):

    enter image description here

提交回复
热议问题