iT邦幫忙

第 11 屆 iT 邦幫忙鐵人賽

DAY 16
0
Modern Web

從Stack Overflow學前端系列 第 16

從StackOverflow上學CODING(16)陣列內使用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比起用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呢?


delete will delete the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined:
delete會刪除物件屬性,但並不會更新陣列長度,且那個欄位會顯示"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. The Chrome dev tools make this distinction clear by printing empty when logging the array.
注意到它也並不是真的把值設為undefined,而比較像是把屬性從陣列移除了,並顯示undefind,從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.
splice則真的會移除元素,並重新更新陣列與長度:

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

上一篇
從StackOverflow上學CODING(15)如何用JS移動html元素
下一篇
從StackOverflow上學CODING(17)如何用JS得知DOM元素出現在目前視窗
系列文
從Stack Overflow學前端30

尚未有邦友留言

立即登入留言