为什么 Array.filter(Number) 在 JavaScript 中过滤零? [英] Why does Array.filter(Number) filter zero out in JavaScript?

查看:20
本文介绍了为什么 Array.filter(Number) 在 JavaScript 中过滤零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从数组中过滤掉所有非数字元素.使用 typeof 时,我们可以看到所需的输出.但是使用 Number,它会过滤掉零.

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.

这是示例(在 Chrome 控制台中测试):

Here's the example (tested in Chrome Console):

[-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,它不会过滤零,这是预期的.

If we use typeof, it doesn't filter zero, which was expected.

// code
[-1, 0, 1, 2, 3, 4, Number(0), '', 'test'].filter(n => typeof n === 'number')
// output
[-1, 0, 1, 2, 3, 4, 0]

我的问题:

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

  1. What is the difference between the 'Number' and 'typeof' approaches?

数字过滤零,但数字"本身包含零,这让我感到困惑.

Number filters zero, but 'Number' itself literally contains zero, and this confuses me.

推荐答案

因为 0 是众多 falsy javascript 中的值

Because 0 is one of the many falsy values in javascript

所有这些条件都将发送到 else 块:

All these conditions will be sent to else blocks:

if (false)
if (null)
if (undefined)
if (0)
if (NaN)
if ('')
if ("")
if (``)

来自 Array.prototype.filter() 文档:

From the Array.prototype.filter() documentation:

filter() 为数组中的每个元素调用一次提供的 callback 函数,并构造一个新数组,其中包含回调为其返回 的所有值强制为真的值

filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true

在您的情况下,回调函数是 Number.所以你的代码相当于:

In your case the callback function is the Number. So your code is equivalent to:

[-1, 0, 1, 2, 3, 4, Number(0), '', 'test'].filter(a => Number(a)) 

// Number(0) -> 0
// Number(Number(0)) -> 0
// Number('') -> 0
// Number('test') -> NaN

filter 函数选择 truthy值(或强制为 true 的值),返回 0NaN 的项目将被忽略.因此,它返回 [-1, 1, 2, 3, 4]

When filter function picks truthy values (or values that coerces to true), the items which return 0 and NaN are ignored. So, it returns [-1, 1, 2, 3, 4]

这篇关于为什么 Array.filter(Number) 在 JavaScript 中过滤零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆