所以,我正在自学 HTML、CSS、JavaScript。我正在浏览箭头函数,并在 MDN 网站上找到了以下代码,但我不确定我是否清楚地理解了 filter() 函数的工作原理。我是这样理解的:“word”是 testFunct() 的参数,参数是 wrds 数组的元素,它们被传递给 testFunct(word)。是否像过滤函数循环遍历数组(参数)的每个元素并评估要求(word.length > 6)?就像正常的(对我来说这是正常的,因为我是初学者)参数/参数对一样,假设您传递 2 个参数,并且有 2 个参数来接收它们。谢谢。
var wrds = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
//const result = words.filter(word => word.length > 6);
//write the arrow function as full function to see if you understood how it works.
const result = wrds.filter(function testFunct(word) {return word.length > 6;});
console.log(result);
prints 'exuberant', 'destruction', 'present
最佳答案
polyfill同一 MDN 页面上的 表示与 ECMA-262 第 5 版中指定的算法完全相同:
if (!Array.prototype.filter){
Array.prototype.filter = function(func, thisArg) {
'use strict';
if ( ! ((typeof func === 'Function' || typeof func === 'function') && this) )
throw new TypeError();
var len = this.length >>> 0,
res = new Array(len), // preallocate array
t = this, c = 0, i = -1;
if (thisArg === undefined){
while (++i !== len){
// checks to see if the key was set
if (i in this){
if (func(t[i], i, t)){
res[c++] = t[i];
}
}
}
}
else{
while (++i !== len){
// checks to see if the key was set
if (i in this){
if (func.call(thisArg, t[i], i, t)){
res[c++] = t[i];
}
}
}
}
res.length = c; // shrink down array to proper size
return res;
};
}
所以,是的,它使用 while
循环迭代数组。
关于javascript - 对filter()函数的澄清;怎么运行的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55629569/