【问题标题】:filter returns an empty array while looping an object's property (array of objects)过滤器在循环对象的属性(对象数组)时返回一个空数组
【发布时间】:2019-08-21 18:13:59
【问题描述】:

我不明白为什么当我尝试遍历对象的数组属性时,过滤器会返回一个空数组。

不过,当我尝试在 getFilteredUsers 方法中执行 console.log(this.users) 时,我可以在其原型中看到 filter 方法...

var userService = {
  currentFilter: "active",
  users: [
    { name: "Alex", status: "active" },
    { name: "Nick", status: "deleted" }
  ],
  getFilteredUsers: function() {
    // console.log(this.users);
    return this.users.filter(function(user) {
      return user.status === this.currentFilter;
    });    
  }
};

console.log(userService.getFilteredUsers()); // []

【问题讨论】:

  • function(user) {...}之后添加.bind(this)
  • 克里斯,你能给我举个例子吗?我正在尝试但失败了。
  • this.users.filter(function(user) { return user.status === this.currentFilter; }.bind(this))
  • 妈的,我改成箭头函数后就搞定了))谢谢!
  • 伙计们,你能不能给我一些资源,这样我就可以获得这些知识?很多课程都展示了如何使用 JS 的东西进行操作,但它们并没有深入到水下岩石。

标签: javascript arrays loops object filter


【解决方案1】:

这是因为

的价值

这个

在过滤器回调中。使用箭头函数来获取正确的值

var userService = {
  currentFilter: "active",
  users: [
    { name: "Alex", status: "active" },
    { name: "Nick", status: "deleted" }
  ],
  getFilteredUsers: function() {
    // console.log(this.users);
    return this.users.filter((user)=> {
      return user.status === this.currentFilter;
    });    
  }
};

console.log(userService.getFilteredUsers()); // []

【讨论】:

    【解决方案2】:

    问题在于 this 对象的范围。它在 filter()callback 函数内部发生变化。您可以尝试两种方法:

    1. 在过滤器回调函数之前在您的函数中创建一个新的过滤器变量,例如:

    var userService = {
        currentFilter: "active",
        users: [{
                name: "Alex",
                status: "active"
            },
            {
                name: "Nick",
                status: "deleted"
            }
        ],
        getFilteredUsers: function() {
            const currentStatus = this.currentFilter;
            return this.users.filter(function(user) {
                return user.status === currentStatus;
            });
        }
    };
    
    console.log(userService.getFilteredUsers()); //[ { name: 'Alex', status: 'active' } ]
    1. 使用es6 箭头函数:

    var userService = {
        currentFilter: "active",
        users: [{
                name: "Alex",
                status: "active"
            },
            {
                name: "Nick",
                status: "deleted"
            }
        ],
        getFilteredUsers: function() {
            return this.users.filter(({
                status
            }) => status === this.currentFilter);
        }
    };
    
    console.log(userService.getFilteredUsers()); // [ { name: 'Alex', status: 'active' } ]

    希望这会有所帮助:)

    【讨论】:

    • 是的!真的很有帮助,谢谢!在使用过滤器功能之前,我也尝试过使用类似 const _this = this 的东西,但我认为这不是最佳做法)
    • 很高兴它有帮助,编码愉快:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-29
    • 2020-10-22
    • 1970-01-01
    相关资源
    最近更新 更多