删除数组元素delete与splice比较

  delete是用来删除对象属性的,但是也可以用来删除数组元素,不过不同于splice,本文将讨论这些不同之处。

delete

delete将删除对象属性,但不会重新索引数组或更新其长度。 这使它看起来好像是未定义的:

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> delete myArray[0]
  true
> myArray[0]
  undefined

请注意,它实际上未设置为undefined值,而是从数组中删除该属性,使其显示为undefined。 通过Chrome开发工具记录打印empty来明确区分。

> myArray[0]
  undefined
> myArray
  [empty, "b", "c", "d"]

splice

myArray.splice(start, deleteCount)实际上删除元素,重新索引数组,并更改其长度。

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> myArray.splice(0, 2)
  ["a", "b"]
> myArray
  ["c", "d"]

 

(0)
上一篇 2019年8月29日 下午10:22
下一篇 2019年8月29日 下午10:56

相关推荐

发表回复

登录后才能评论