JavaScript array slice versus delete

2019-02-17 22:39发布

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'

2条回答
ゆ 、 Hurt°
2楼-- · 2019-02-17 23:02

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']

查看更多
Ridiculous、
3楼-- · 2019-02-17 23:10

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

查看更多
登录 后发表回答