Why does Array.filter(Number) filter zero out in JavaScript?

前端 未结 9 1972
时光说笑
时光说笑 2020-12-10 00:10

I\'m trying to filter all non-numeric elements out from an array. We can see the desired output when using typeof. But with Number, it filters zero out.

Here\'s the

9条回答
  •  再見小時候
    2020-12-10 00:52

    The reason for this behavior is that 0, null, undefined, NaN is equivalent to false in JavaScript so, in the first case:

    [-1, 0, 1, 2, 3, 4, Number(0), '', 'test'].filter(Number);
    

    when used Number as one of the params in the filter, it returns the number itself. So when 0 is passed it returns 0 which javascript understands as false. So, it returns

    [-1, 1, 2, 3, 4]
    

    So to be on the safe side it is advised to use Number.isFinite instead of just Number.

    [-1, 0, 1, 2, 3, 4, Number(0), '', 'test'].filter(Number.isFinite);
    

    Gives same results as

    [-1,0,1,2,3,4, Number(0), '','test'].filter(n=> typeof n === 'number');
    

    would give.

提交回复
热议问题