Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

javascript - 在JavaScript中删除数组元素-Delete与Splice(Deleting array elements in JavaScript - delete vs splice)

What is the difference between using the delete operator on the array element as opposed to using the Array.splice method ?

(在数组元素上使用delete运算符与使用Array.splice方法有什么Array.splice ?)

For example:

(例如:)

myArray = ['a', 'b', 'c', 'd'];

delete myArray[1];
//  or
myArray.splice (1, 1);

Why even have the splice method if I can delete array elements like I can with objects?

(如果可以像删除对象一样删除数组元素,为什么还要使用splice方法?)

  ask by lYriCAlsSH translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

delete will delete the object property, but will not reindex the array or update its length.

(delete将删除对象属性,但不会为数组重新索引或更新其长度。)

This makes it appears as if it is undefined:

(这使得它看起来好像是未定义的:)

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

Note that it is not in fact set to the value undefined , rather the property is removed from the array, making it appear undefined.

(请注意,实际上并没有将其设置为undefined ,而是从数组中删除了该属性,使其显得未定义。)

The Chrome dev tools make this distinction clear by printing empty when logging the array.

(Chrome开发人员工具通过在记录阵列时将其打印为empty使这一区别清晰可见。)

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

myArray.splice(start, deleteCount) actually removes the element, reindexes the array, and changes its length.

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...