JS在循环内应用函数

JS apply function inside loop

下面的代码是 jQuery 的每个方法

的 vanilla JS 等价物
NodeList.prototype.each = function(fn) {
  for (var i = 0; i < this.length; i++) {
    fn.apply(this[i], [i, this[i]]);
  }
  return this;
};

有人能解释一下为什么调用带有参数索引“i”的函数吗 代码:fn.apply(这​​个[i], [i, 这个[i]]);

func.apply(thisArg, [ argsArray]):

thisArg: The value of this provided for the call to func.

Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed. This argument is required.

argsArray: Optional An array-like object, specifying the arguments with which func should be called, or null or undefined if no arguments should be provided to the function.

就你而言:

this[i] 是属于 NodeList 的当前元素。

each 是添加到 NodeList 的新函数您可以稍后使用,例如 .querySelectorAll('p')

这是一个例子:

NodeList.prototype.each = function(fn) {
    for (var i = 0; i < this.length; i++) {
        console.log('this[' + i + ']=' + this[i].outerHTML);
        fn.apply(this[i], [i, this[i]]);
    }
    return this;
};

document.querySelectorAll('p').each(function(idx, ele) {
    console.log('each call: idx=' + idx + ' and ele=' + ele.outerHTML);
})
<p>1</p>
<p>2</p>
<p>3</p>