【问题标题】:lodash Array _includeslodash 数组 _includes
【发布时间】:2019-08-22 22:48:36
【问题描述】:

如何在 lodash 中传递一个数组?

users = [{
            name: 'aaa', age: 22
},{
            name: 'bbb', age: 33
},{
            name: 'ccc', age: 44
},];
this.selection = _.filter(users, function(p) {
       return _.includes(['aaa', 'bbb'], p.name);           
    });

上面的代码运行良好,我得到了用户 aaa 和 bbb 的所有详细信息

但是,如果我做类似的事情 this.testuser = ['aaa', 'bbb'];

this.selection = _.filter(users, function(p) {
           return _.includes(this.testuser, p.name);           
        });

它抱怨 this.testuser?

谢谢!

【问题讨论】:

  • this.selection = _.filter(users, (p) => { return _.includes(this.testuser, p.name); });
  • 谢谢,效果很好!

标签: javascript arrays lodash


【解决方案1】:

您的问题是在不同上下文中调用的回调中访问this。您可以使用箭头函数或绑定来解决它。

但是,您可以解决从一个数组中选择项目的问题,而不是解决this 的问题,方法是使用来自另一个数组的值,使用 lodash 的_.intersectionWith()。由于你没有在回调函数中使用this.testuser,所以你不会遇到同样的问题。

var users = [{"name":"aaa","age":22},{"name":"bbb","age":33},{"name":"ccc","age":44}];

var obj = {
  testuser: ['aaa', 'bbb'],
  selection(users) {
    return _.intersectionWith(users, this.testuser, function(a, b) {
      return a.name === b;
    });
  }
};

console.log(obj.selection(users));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

【讨论】:

    【解决方案2】:

    function 内,范围不同意味着this 指的是别的东西(大多数情况下是window 对象)所以你不能在函数内部访问this.testuser,因为它是在不同的范围内定义的.

    要使其正常工作,请使用arrow function(它没有自己的this 绑定)而不是traditional function 语法。

    this.selection = _.filter(users, p => _.includes(this.testuser, p.name));
    

    您可以使用本机 Javascript 函数来完成,而无需 lodash。

    this.selection = users.filter(p => this.testuser.includes(p.name));
    

    【讨论】:

      【解决方案3】:

      函数内部的this 将绑定到没有testuser 变量的匿名函数。因此,您可以使用评论中提到的arrow function,也可以使用bind

      this.selection = _.filter(users,
          (function(p) {
              return _.includes(this.testuser, p.name);           
          }).bind(this));
      

      【讨论】:

        【解决方案4】:

        正如 @Pranav C Balan 在他们的评论中指出的那样,关键字 this 绑定到您传递给 _.includes() 的函数。如果你提供一个箭头函数,像这样,它将绑定到你的类:

        this.selection = _.filter(users, (p) => { return _.includes(this.testuser, p.name); });
        

        @brk

        所述,另一种选择是使用 Function.prototype.bind()

        【讨论】:

          猜你喜欢
          • 2018-08-09
          • 2017-02-22
          • 2014-08-12
          • 2015-09-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多