I'm trying to filter all non-numeric elements out from an array.
(我正在尝试从数组中过滤掉所有非数字元素。)
We can see the desired output when using typeof.(使用typeof时,我们可以看到所需的输出。)
But with Number, it filters zero out.(但是使用Number可以过滤掉零。)
Here's the example (tested in Chrome Console):
(下面是示例(已在Chrome控制台中测试):)
[-1, 0, 1, 2, 3, 4, Number(0), '', 'test'].filter(Number)
// Which output with zero filtered out:
[-1, 1, 2, 3, 4] // 0 is filtered
If we use typeof, it doesn't filter zero, which was expected.
(如果我们使用typeof,它不会过滤零,这是预期的。)
// code
[-1, 0, 1, 2, 3, 4, Number(0), '', 'test'].filter(n => typeof n === 'number')
// output
[-1, 0, 1, 2, 3, 4, 0]
My question:
(我的问题:)
What is the difference between the 'Number' and 'typeof' approaches?
(“数量”和“类型”方法之间有什么区别?)
Number filters zero, but 'Number' itself literally contains zero, and this confuses me.
(数字过滤为零,但是“数字”本身实际上包含零,这使我感到困惑。)
ask by imckl translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…