使用对象而不是回调函数时,过滤器函数如何工作?

时间:2019-02-28 19:28:04

标签: javascript

我试图使用.filter(String)过滤出空值并获得成功:

['foo','bar','',''].filter(String);
// ['foo','bar']

这是我期望的结果,并且按预期工作。

但是突然看起来更深了:

'' instanceof String // false
'foo' instanceof String // false
''.constructor.prototype // String.prototype
'foo'.constructor.prototype // String.prototype

因此,我们看不到任何区别。感到惊讶的是这实际上是如何工作的。考虑到以上情况,它应该只返回['foo','bar','',''],因为所有字符串值都如此。

编辑:

我删除了答案,只是因为我认为这还不能完全满足:

过滤器函数最后满足布尔值。

Boolean('') // false, so remove
Boolean('foo') // true, so keep it

字符串是构造函数-@Nina Scholz在评论中指出的函数。

嗯,它不是构造函数-@Bergi指出。同意但是现在令.filter(String)变成.filter(s=>String(s))的情况完全感到惊讶-因为String根本不是函数调用。

2 个答案:

答案 0 :(得分:2)

Array ( [472] => Array ( [totalc] => 243.65 [condition] => 1 ) [505] => Array ( [totalc] => 189.225 [condition] => ) ) 无关。

instanceof String

相同
['foo','bar','',''].filter(String);

['foo','bar','',''].filter(a => String(a)); 返回一个空字符串String('')。这就是 falsy 值。因此,它们之所以退出filtered,是因为:

  

''对数组中的每个元素调用一次提供的回调函数,并构造一个新的数组,该数组的所有值都由回调返回强制为true的值

因此,如果数组中有filter()(数字),即使0也不会被过滤。因为0 instance of String === false返回了String(0)值的"0"

答案 1 :(得分:1)

例如,您可以使用其他构造函数,例如BooleanStringArrayObject。回调返回不同的值,例如

  • Boolean仅返回truthy个值,

  • String返回除空字符串'',具有单个空字符串['']和空数组[]的所有值,

  • ArrayObject返回将全部返回,

  • Number转换为数字后仅返回真实值。

var array = [-1, 0, 1, NaN, Infinity, '', 'a', 'b', true, false, undefined, null, {}, { a: 1 }, [], [''], [1], [1, 2]];

console.log(array.filter(Boolean));
console.log(array.filter(String));
console.log(array.filter(Array));
console.log(array.filter(Object));
console.log(array.filter(Number));
.as-console-wrapper { max-height: 100% !important; top: 0; }