尝试:
articles.filter(article =>
Object.values(article).every(x => (x !== null))
&& article.title.length <= 90
)
让我们分解一下:
articles.filter(article => ...)
.filter
是一种函数属性类型,接受一个回调参数,对于每个项目都会调用它。本质上,我们正在传递函数 - 而不是立即执行它,它可以在适当的时候调用它。这有点像:
let a = alert
我们并没有调用
alert
函数,只是将它保存在一个变量中。对于
.filter
,我们将其用作伪变量 - 一个参数。在内部,所有的
.filter
实际上只是:
Array.prototype.filter(callbackFunc) {
newArr = [];
for (i=0;i<this.length;i++){
if (callbackFunc(this[i]) === false){
newArr.push(this[i]);
}
}
return newArr;
}
下一个需要解释的部分是我们正在使用的实际回调函数。它是使用ES6箭头语法定义的,但它等效于:
articles.filter(function(article){
return Object.values(article).every(x => (x !== null))
&& article.title.length <= 90
})
回调函数的第一行
Object.values(article).every(x => (x !== null))
,可以拆分为:
let values = Object.values(article); // Get the value of all of the keys in the object
function checkFunction(item){ // Define a helper function
return (x !== null); // Which returns if an item is _not_ null.
}
let result = values.every(checkFunction); // Run `checkFunction` on every item in the array (see below), and ensure it matches _all_ of them.
最后,我们只需要澄清一下every
的作用。这是另一个函数式JS的例子,其中函数接受回调函数作为参数。内部代码如下:
Array.prototype.every(callbackFunc) {
for (i=0;i<this.length;i++){
if (callbackFunc(this[i]) === false){
return false;
}
}
return true;
}
"
&& article.title.length <= 90
应该很容易理解:当 .every
返回一个布尔值 (true
或 false
),只有当回调函数同时满足第二个条件时,才会将 true
返回到 filter
中,即如果 every
返回 true
并且 article.title.length <= 90
。
"
some
方法而不是every
? - fellinlovewithamanevery
,因为some
只需要至少一个“真值”,而您想要所有值都是“真值”。 - Matthew Liu