小编imc*_*ckl的帖子

为什么Array.filter(Number)在JavaScript中过滤掉了?

我正在尝试从数组中过滤掉所有非数字元素.使用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)

我的问题:

  1. 'Number'和'typeof'方法有什么区别?

  2. 数字过滤零,但'数字'本身确实包含零,这让我感到困惑.

javascript numbers typeof

42
推荐指数
3
解决办法
2494
查看次数

标签 统计

javascript ×1

numbers ×1

typeof ×1