remove trailing elements from array that are equal to zero - better way

后端 未结 2 1889
醉梦人生
醉梦人生 2021-01-18 20:52

I have very long array containing numbers. I need to remove trailing zeros from that array.

if my array will look like this:

var arr = [1,2,0,1,0,1,0         


        
2条回答
  •  渐次进展
    2021-01-18 21:40

    Assuming:

    var arr = [1,2,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
    

    You can use this shorter code:

    while(arr[arr.length-1] === 0){ // While the last element is a 0,
        arr.pop();                  // Remove that last element
    }
    

    Result:

    arr == [1,2,0,1,0,1]
    

提交回复
热议问题