ES6与ReactJS数组过滤问题:按指定索引匹配后调用createOptions函数
修正数组过滤逻辑与语法错误
嘿,我来帮你搞定这个问题!你的代码里有两个关键问题需要修正,咱们一步步来:
1. 第一个 filter 的语法错误
你现在写的 .filter(this.isEligible(selectedIndex)) 是直接执行了 isEligible 函数,而 filter 要求传入的是一个返回布尔值的回调函数,不是函数执行的结果。如果 isEligible 需要接收当前 item 和 selectedIndex 作为参数,你得把它包装成一个回调:
.filter(item => this.isEligible(item, selectedIndex))
2. 第二个 filter 的逻辑调整
你的需求是仅当索引等于 selectedIndex 或 selectedIndex+2 时才调用 createOptions,还要用它的返回值决定是否保留这个item。这里要注意一个容易踩的坑:你说的索引是原数组的索引还是过滤后的新数组索引?两种情况的写法不一样:
情况一:基于过滤后的新数组索引判断
如果是过滤后的数组索引,直接在第二个 filter 里加条件判断即可:
const newArr = items .filter(item => this.isEligible(item, selectedIndex)) // 修正后的第一个过滤 .filter((item, index) => { // 只在符合索引条件时调用createOptions if (index === selectedIndex || index === selectedIndex + 2) { return this.createOptions(item, index, selectedItem); } // 这里根据你的需求调整:不符合索引条件的item是过滤掉还是保留? // 下面的示例是过滤掉,如果你想保留就改成return true return false; });
情况二:基于原数组的索引判断(更常见)
因为过滤后的数组索引会和原数组不一致,如果你要判断的是原数组的索引,得先把原索引和item绑定在一起,最后再还原:
const newArr = items // 先把原数组索引和item绑定成对象 .map((item, originalIndex) => ({ item, originalIndex })) .filter(({ item }) => this.isEligible(item, selectedIndex)) .filter(({ item, originalIndex }) => { // 用原索引做判断 if (originalIndex === selectedIndex || originalIndex === selectedIndex + 2) { return this.createOptions(item, originalIndex, selectedItem); } return false; // 同样,按需调整是否保留不符合条件的item }) // 最后把结构还原成原item的格式 .map(({ item }) => item);
额外说明
如果你的需求是「符合索引条件的调用createOptions来决定是否保留,不符合索引条件的直接保留」,那把第二个filter里的 return false 改成 return true 就行啦。
内容的提问来源于stack exchange,提问作者Sunny
相关产品推荐
相关产品推荐

