Javascript 筛选器不使用匿名函数
我正在尝试学习react,因此我知道这不是制作副本的最佳方法,但为什么以下方法不起作用:Javascript 筛选器不使用匿名函数,javascript,reactjs,Javascript,Reactjs,我正在尝试学习react,因此我知道这不是制作副本的最佳方法,但为什么以下方法不起作用: var allItems = this.state.items; allItems =allItems.filter(function(e){return e;}); 我一直认为过滤器不是一个函数,因为这个.state.items是一个对象,而不是数组,您需要像这样循环键: var filteredArray = []; Object.keys(allItems).forEach(function(key
var allItems = this.state.items;
allItems =allItems.filter(function(e){return e;});
我一直认为过滤器不是一个函数,因为
这个.state.items
是一个对象,而不是数组,您需要像这样循环键:
var filteredArray = [];
Object.keys(allItems).forEach(function(key) {
// do something with each item
console.log(key + ': ' + allItems[key]);
// like add it to a filtered array, conditionally if you want to:
filteredArray.push(allItems[key]);
});
确保
allItems
是一个数组。是否确定this.state.items
是一个数组?也许最初需要将其设置为[]
?您可以将其减少为allItems.filter(e=>e)
,尽管我不明白为什么,您返回的是所有内容,没有任何内容被“过滤”。您正在尝试将某些内容转换为数组吗?谢谢,allitems是一个对象{}这是您的问题,filter
a数组方法,而不是对象方法