我正在尝试从数组中过滤掉所有非数字元素.使用typeof时,我们可以看到所需的输出.但是使用Number,它会过滤掉零.
以下是示例(在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
Run Code Online (Sandbox Code Playgroud)
如果我们使用typeof,它不会过滤零,这是预期的.
// code
[-1, 0, 1, 2, 3, 4, Number(0), '', 'test'].filter(n => typeof n === 'number')
// output
[-1, 0, 1, 2, 3, 4, 0]
Run Code Online (Sandbox Code Playgroud)
我的问题:
'Number'和'typeof'方法有什么区别?
数字过滤零,但'数字'本身确实包含零,这让我感到困惑.