Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

javascript - 为什么Array.filter(Number)在JavaScript中过滤掉零?(Why does Array.filter(Number) filter zero out in JavaScript?)

I'm trying to filter all non-numeric elements out from an array.

(我正在尝试从数组中过滤掉所有非数字元素。)

We can see the desired output when using typeof.

(使用typeof时,我们可以看到所需的输出。)

But with Number, it filters zero out.

(但是使用Number可以过滤掉零。)

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

(下面是示例(已在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

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

(如果我们使用typeof,它不会过滤零,这是预期的。)

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

My question:

(我的问题:)

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

    (“数量”和“类型”方法之间有什么区别?)

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

    (数字过滤为零,但是“数字”本身实际上包含零,这使我感到困惑。)

  ask by imckl translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Because 0 is one of the many falsy values in javascript

(因为0是javascript中许多falsy值之一)

All these conditions will be sent to else blocks:

(所有这些条件将被发送到else块:)

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

From the Array.prototype.filter() documentation:

(从Array.prototype.filter()文档中:)

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

(filter()为数组中的每个元素调用一次提供的callback函数,并构造一个所有值的新数组,对于这些值,回调将返回强制为true)

In your case the callback function is the Number .

(在您的情况下,回调函数是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

When filter function picks truthy values (or values that coerces to true ), the items which return 0 and NaN are ignored.

(当filter函数选择真实值(或强制转换true值)时,返回0NaN的项将被忽略。)

So, it returns [-1, 1, 2, 3, 4]

(因此,它返回[-1, 1, 2, 3, 4])


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...