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

前端 未结 6 1862
不思量自难忘°
不思量自难忘° 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:09

    Ok.. fixed this now as the array was still allocated.

    I needed to basically do:

    var newCar = new Array();
    for (i = 0 ; i < tblSize -2; i ++)
    {
        newCar[i]=data.Dealer.car[i];
    }
    data.Dealer.car = newCar;
    
    0 讨论(0)
  • 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()

    0 讨论(0)
  • 2020-12-03 18:13

    I think you're looking for this:

    var arr = [0,1,2,3,4];
    
    alert( arr.splice( 2, 1 ) ); // alerts 2, the element you're removing
    alert( arr ) // alerts 0,1,3,4  - the remaining elements
    

    here's a MDC reference

    0 讨论(0)
  • 2020-12-03 18:14

    JavaScript arrays aren't sparse, if you have a 0 and a 2, then element 1 must exist. Meaning the length is going to be 3.

    0 讨论(0)
  • 2020-12-03 18:21

    If you want to remove an item, use the splice method:

    alert(data.Dealer.car.length);
    data.Dealer.car.splice(1, 1);
    alert(data.Dealer.car.length);
    

    But notice that the indices have changed.

    0 讨论(0)
  • 2020-12-03 18:23

    Array.shift() would remove the first item from the array and make it shorter. Array.pop() will remove the last item.

    0 讨论(0)
提交回复
热议问题