【问题标题】:Jquery - Passing a function to the filter function, with two parametersJquery - 将一个函数传递给过滤函数,带有两个参数
【发布时间】:2016-12-24 23:18:18
【问题描述】:

在过滤器和非过滤器等Jquery函数中,您可以传递一个传递两个参数的函数。我在看一本书,它说第一个参数是当前元素的索引,而第二个参数是当前元素。我很困惑。使用第二个参数和使用 this 关键字有什么区别。 this 关键字不也指向当前元素吗?这是否指向当前元素,作为参考,而元素参数是元素。我用哪一个?

谢谢!

【问题讨论】:

    标签: javascript jquery function filter


    【解决方案1】:
    array.filter(function(currentValue, index, arr), thisValue)
    

    currentValue(Required)- 当前元素的值

    index(可选)- 当前元素的数组索引

    arr(可选)- 当前元素所属的数组对象

    thisValue(Optional)- 传递给函数以用作其“this”值的值。 如果此参数为空,则值“undefined”将作为其“this”值传递

    【讨论】:

    • OP 不是在问Array.prototype.filter(),而是在问$.fn.filter
    【解决方案2】:

    箭头函数保留外部作用域中的this 关键字。

    常规函数会得到更新的this

    sn-p 中的示例。

    var $body = $(document.body);
    
    console.log("Testing arrow functions");
    $body.each((idx, el) => {
      console.log(el === this);
      });
    
    console.log("Testing regular functions");
    
    $body.each(function(idx, el) {
      console.log(el === this);
      });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

    【讨论】:

      猜你喜欢
      • 2014-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-25
      • 1970-01-01
      • 2011-03-09
      相关资源
      最近更新 更多