简体   繁体   English

从Javascript“过滤器”函数返回“空”值

[英]Returning “null” value from Javascript “filter” function

Let's say i have the following array: arr = [1, 2, 0, null, 4] , and i want to filter all the "0" in the array. 假设我有以下数组: arr = [1, 2, 0, null, 4] ,并且我想过滤数组中的所有“ 0”。 An example code would be: 示例代码为:

arr.filter((val) => {return val !== 0})
//>> [1, 2, null, 4]

It works just fine. 它工作正常。 But if i use an if statement instead, the "null" value isn't returned: 但是,如果我改用if语句,则不会返回“ null”值:

arr.filter((val) => {if(val !== 0) return val})
//>> [1, 2, 4]

It only works if i return an array containing the "value": 它仅在我返回包含“值”的数组时才有效:

arr.filter((val) => {if(val !== 0) return [val]})
//>> [1, 2, null, 4]

Could anybody explain why when using an if statement the "null" only is returned if it is in an array? 有人可以解释为什么在使用if语句时,如果仅在数组中返回“ null”吗?

An item will be included in the resulting array if the value returned from the filter callback is truthy. 如果从filter回调返回的值是true,则项目将包含在结果数组中。

return val !== 0

will return false if val is 0, and true otherwise. 如果val为0,将返回false ,否则返回true

if(val !== 0) return val

will return undefined if the val is 0 , and will return the val otherwise. 如果val0将返回undefined ,否则返回val So, if the val is not 0 , but is still falsey (like null ), it won't be included in the result. 因此,如果val不为0 ,但仍然为假(如null ),则它将不包含在结果中。

But arrays are always truthy (no matter what values they contain), so 但是数组总是真实的(不管它们包含什么值),所以

if(val !== 0) return [val]}

will always result in non- 0 values being included in the final array. 始终导致最终数组中包含非0值。

 console.log(Boolean(null)); console.log(Boolean([null])); 

Well filter callback is supposed to return true or false. 好的过滤器回调应该返回true或false。

You are not returning true or false. 您没有返回true或false。 So it converts your item into a boolean. 因此,它将您的项目转换为布尔值。

So null is falsly an array would be truthy. 所以null是虚假的,数组将是真实的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM