当我尝试遍历对象的array属性时,我不明白为什么filter会返回一个空数组。
但是,当我尝试在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()); // []
答案 0 :(得分: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()); // []
答案 1 :(得分:1)
问题在于此对象的范围。它会在 filter()的回调函数内部更改。您可以尝试两种方式:
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' } ]
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' } ]
希望这会有所帮助:)