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

前端 未结 9 1989
时光说笑
时光说笑 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:55

    When you're using Number in filter, Actually it is passing each item of Array to Number constructor and in case of string or 0 Number will return NaN or 0 and both of them are false so filter is filtering out both of them

    whereas when you're using typeof then 0 has "number" type so it is returning true and filter method doesn't filtering it out

提交回复
热议问题