为了账号安全,请及时绑定邮箱和手机立即绑定

JS在循环内应用函数

JS在循环内应用函数

HUWWW 2023-03-18 16:48:11
下面的代码是 vanila JS 等价于 jQuery 的每个方法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(this[i], [i, this[i]]);
查看完整描述

1 回答

?
守候你守候我

TA贡献1802条经验 获得超10个赞

func.apply(thisArg, [argsArray]) :

thisArg:为调用func提供的this的值。

请注意,这可能不是该方法看到的实际值:如果该方法是非严格模式代码中的函数,则 null 和 undefined 将被替换为全局对象,原始值将被装箱。此参数是必需的。

argsArray:可选 一个类似数组的对象,指定应调用 func 的参数,如果不应向函数提供参数,则指定 null 或 undefined。

就你而言:

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

每个都是添加到 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>


查看完整回答
反对 回复 2023-03-18
  • 1 回答
  • 0 关注
  • 96 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信