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

前端 未结 9 1880
时光说笑
时光说笑 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 01:03

    To prevent a falsy zero from filtering, you could use another callback for getting only numerical values: Number.isFinite

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

    0 讨论(0)
  • 2020-12-10 01:07

    For preventing a falsy zero from filtering, you could use another callback for getting only numerical values: Number.isFinite

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

    0 讨论(0)
  • 2020-12-10 01:15

    Zero is a falsey value. The typeof is always returning a boolean value. When the number 0 is returned, it is returning to the test, and therefore coming back as false, so the number zero is filtered out.

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