Array.prototype.filter()何时检查伪造的值? [英] At which point does Array​.prototype​.filter() check for falsy values?

查看:85
本文介绍了Array.prototype.filter()何时检查伪造的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发现了此强大功能,删除了

I stumbled upon this great function to remove falsy values from an array:

let other = array.filter(item => item);

但是我不知道这是如何工作的.据我了解 Array的解释在MDN上找到.prototype..filter():

But I don't understand how this can work. As far as I understand the explanation of Array​.prototype​.filter() found on the MDN:

filter()方法创建一个新数组,其中包含所有通过提供的功能实现的测试的元素.

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

以下代码应该与上面的代码相同(并且确实提供相同的输出):

The following code should be the same thing as the one found above (and it does provide the same output):

function foo(item) {
  return item;
}

let other = array.filter(foo);

但是foo()仅返回所有伪造的值,如您在下面的代码片段中所见(按预期). 如果伪造的值确实通过了提供的功能 ,什么时候进行过滤?

But foo() just returns all the falsy values as you can see in the snippet below (as expected). When does the filtering take place if the falsy values DO pass the provided function?

let array = ['foo', undefined, false, 'bar'];

function foo(item) {
  return item;
}

array.forEach(item => console.log(foo(item)));

编辑:我的问题存在一些误解:我知道我没有在代码段中使用filter().这是因为其唯一目的是表明所有值 pass 通过foo()函数,这在当时似乎与以下内容矛盾: [...]通过提供的功能实现的测试.

There has been some misunderstanding about my question: I am aware that I am not using filter() in the snippet. This is because its only purpose is to show that all the values pass the foo()-function which, at the time, seemed like a contradiction to: [...] all elements that pass the test implemented by the provided function.

查看Polyfill和说明,我现在理解了它为何按其方式工作.谢谢@adiga.我不完全理解 [...]返回一个强制为true的值,因为英语不是我的母语,但是我想这意味着 [...]返回的含义只是真实的值.

Looking at the Polyfill and the Description I now understand why it works the way it does. Thank you, @adiga. I did not fully understand [...] returns a value that coerces to true since English is not my first language but I guess it means something along the lines of [...] returns only the truthy values.

推荐答案

我不确定我是否正确理解了问题,但是filter仅返回过滤器回调返回被强制为<的值c5>(即非虚假).

I'm not sure if I understand the question correctly, but filter returns only the values for which the filter callback returns a value that gets coerced to true (ie non-falsy).

这就是为什么过滤掉伪造的值仅需要filter函数返回值本身的原因.

That's why filtering out falsy values simply requires the filter function to return the value itself.

(回调函数还可以显式地返回带有!!value的布尔值,这将执行相同的操作.)

(The callback could also explicitly return a boolean with !!value, which would do the same thing.)

这篇关于Array.prototype.filter()何时检查伪造的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆