为什么Array.filter(Number)在JavaScript中过滤掉零? [英] Why does Array.filter(Number) filter zero out in 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]
我的问题:
-
数字"和类型"方法有什么区别?
What is the difference between the 'Number' and 'typeof' approaches?
数字过滤为零,但是数字"本身实际上包含零,这使我感到困惑.
Number filters zero, but 'Number' itself literally contains zero, and this confuses me.
推荐答案
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()
文档:
filter()
会为数组中的每个元素调用一次提供的callback
函数,并为所有值构造一个新数组,所有这些值的回调将返回强制为true的值
filter()
calls a providedcallback
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
函数选择真实的值(或强制为true
),则返回0
和NaN
的项目将被忽略.因此,它返回[-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屋!