Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript array slice versus delete

Is there any reason why one should be used over the other?

e.g.

var arData=['a','b','c'];
arData.slice(1,1);//removes 'b'

var arData=['a','b','c'];
delete arData[1];//removes 'b'
like image 459
Francisc Avatar asked Apr 25 '12 23:04

Francisc


2 Answers

delete leaves you with [ 'a', undefined, 'c' ]

splice leaves you with [ 'a', 'c' ]

slice doesn't do anything to the original array :) But it returns [ 'b' ] in your code

like image 171
Nobody Avatar answered Sep 22 '22 06:09

Nobody


delete only makes that certain location of the array undefined but the array still contains 3 items: ['a',undefined,'c']

the other way to do it is splice and not slice. splice totally removes that item and it's location, so you end up with ['a','c']

like image 33
Joseph Avatar answered Sep 23 '22 06:09

Joseph