Why doesn’t deleting from a Javascript array change its length?

前端 未结 6 1867
不思量自难忘°
不思量自难忘° 2020-12-03 17:55

I have an array:

data.Dealer.car[0]
data.Dealer.car[1]
data.Dealer.car[2]

If I do this:

alert(data.Dealer.car.length);
dele         


        
6条回答
  •  抹茶落季
    2020-12-03 18:11

    Building on what @Ray Hidayat posted:

    JavaScript arrays are sparse. If you have an array of length 3, deleting the reference at [1] will simply "unset" that item, not remove it from the array, or update that array's length. You could accomplish the same with

    myArray = [0, , 2, , , , ];  // length 6; last three items undefined
    

    Here's a Fiddle: http://jsfiddle.net/WYKDz/

    NOTE: removing items from the middle of large arrays can be computationally intensive. See this post for more info: Fastest way to delete one entry from the middle of Array()

提交回复
热议问题