Why does Array.filter(Number) filter zero out in JavaScript?(为什么 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]
我的问题:
'Number' 和 'typeof' 方法有什么区别?
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 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
函数选择 truthy值(或强制为 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 中过滤零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 Array.filter(Number) 在 JavaScript 中过滤零?


基础教程推荐
- 如何在特定日期之前获取消息? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01