如何通过索引获取对象内数组并访问/搜索其元素?
解决方案
修改后的代码实现
let testObj = { tableA : [0,0,0,0,1,1,1,1], tableB : [0,0,1,1,0,0,1,1], tableC : [0,1,0,1,0,1,0,1], key : function(n, elementIndex){ const targetArr = this[Object.keys(this)[n]]; // 传入第二个索引时返回对应元素,否则返回整个数组 return elementIndex !== undefined ? targetArr[elementIndex] : targetArr; }, // 遍历搜索数组元素的方法,示例为查找目标值的所有索引 searchArray: function(arrIndex, targetVal) { const arr = this.key(arrIndex); const matchIndices = []; arr.forEach((val, idx) => { if (val === targetVal) { matchIndices.push(idx); } }); return matchIndices; } } // 测试用例 console.log(testObj.key(1)); // 输出 [0,0,1,1,0,0,1,1] console.log(testObj.key(1, 0)); // 输出 0 console.log(testObj.searchArray(0, 1)); // 输出 [4,5,6,7]
功能说明
- 双索引获取元素:
key方法新增可选参数elementIndex,当传入该参数时直接返回目标数组对应位置的元素;未传入时保留原有逻辑返回整个数组,兼容旧调用方式。 - 遍历搜索元素:新增
searchArray方法,传入数组索引和要搜索的值,遍历数组收集所有匹配值的索引。如果需要其他搜索逻辑(如只返回第一个匹配项、判断值是否存在),修改方法内部的遍历逻辑即可。
内容的提问来源于stack exchange,提问作者Erblin Krasniqi
相关产品推荐
相关产品推荐

