count empty values in array

后端 未结 3 948
隐瞒了意图╮
隐瞒了意图╮ 2020-12-10 05:17

Given an array:

var arr = [1,,2,5,6,,4,5,6,,];

Count how many empty values is has: (length - length after removing the emp

3条回答
  •  暖寄归人
    2020-12-10 05:42

    Looks good to me.

    You could also do:

    var empties = arr.reduce(function(x, y){ return x-1; }, arr.length);
    

    Also, if you don't mind sorting the array, you might get a little added performance out of:

    arr.sort();
    for (var j=arr.length-1; j > 0 && arr[j] === undefined; j--) {}
    var empties = arr.length-j-1;
    

提交回复
热议问题