[英]How does this function remove all falsy values from an array?
function bouncer( arr ){
return arr.filter( function( value ){
return value;
});
This function removes all falsy values from an array. 此函数从数组中删除所有伪造的值。 I don't understand how it works.
我不明白它是如何工作的。 Does filter automatically only return non-falsy values?
过滤器是否仅自动返回非伪造的值?
Because filter
calls the callback with each value from the array, and builds a new array that includes only the values for which filter
returned a truthy value. 因为
filter
用数组中的每个值调用回调,并构建一个新数组,该数组仅包含filter
返回真实值的值。 So returning the value from the callback only retains truthy values (non-falsy ones), because when the callback returns a falsy value, filter
leaves that entry out of the array it builds. 因此,从回调返回值仅保留真实值(非虚假的值),因为当回调返回虚假值时,
filter
会将该项从其构建的数组中删除。
For details on how filter
works, see MDN (readable) or the specification (markedly less so, but definitive). 有关
filter
如何工作的详细信息,请参见MDN (可读)或规范 (明显较少,但权威)。
You could use Boolean
as well for filtering truthy values. 您也可以使用
Boolean
值过滤真实值。
It returns a boolean value for every value. 它为每个值返回一个布尔值。
The value passed as the first parameter is converted to a boolean value, if necessary.
如果需要,作为第一个参数传递的值将转换为布尔值。 If the value is omitted or is
0
,-0
,null
,false
,NaN
,undefined
, or the empty string (""
), the object has an initial value offalse
.如果该值被省略或为
0
,-0
,null
,false
,NaN
,undefined
或空字符串(""
),则该对象的初始值为false
。 If the DOM objectdocument.all
is passed as a parameter, the new boolean object also has an initial value offalse
.如果将DOM对象
document.all
作为参数传递,则新的布尔对象也将具有false
初始值。 All other values, including any object or the string"false"
, create an object with an initial value oftrue
.所有其他值,包括任何对象或字符串
"false"
,都会创建一个初始值为true
的对象。
function bouncer(arr) {
return arr.filter(Boolean);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.