Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
173
rated 0 times [  179] [ 6]  / answers: 1 / hits: 16428  / 12 Years ago, thu, may 24, 2012, 12:00:00

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)[0];


Second:



var element = my_array.shift();


I want to substitute the first by the second, in my own code, to improve readability. Can I do this?


More From » arrays

 Answers
18

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


[#85372] Wednesday, May 23, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zackeryzainv

Total Points: 61
Total Questions: 102
Total Answers: 99

Location: Andorra
Member since Sat, May 27, 2023
1 Year ago
;