【发布时间】:2018-12-25 06:52:06
【问题描述】:
我正在尝试从数组中过滤掉所有非数字元素。使用 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
如果我们使用 typeof,它不会过滤零,这是预期的。
// code
[-1, 0, 1, 2, 3, 4, Number(0), '', 'test'].filter(n => typeof n === 'number')
// output
[-1, 0, 1, 2, 3, 4, 0]
我的问题:
'Number' 和 'typeof' 方法有什么区别?
数字过滤零,但“数字”本身包含零,这让我很困惑。
【问题讨论】:
标签: javascript numbers typeof