JavaScript实现:提取数组中奇数索引位置的奇数元素
问题解决:提取数组中奇数索引位置的奇数元素
修正后的代码
直接修改原代码,利用forEach的第二个参数获取元素索引,同时添加索引为奇数的判断条件:
function codeNation(arr) { let newArr = []; arr.forEach(function(value, index) { // 同时满足:索引为奇数 且 元素本身是奇数 if (index % 2 !== 0 && value % 2 !== 0) { newArr.push(value); } }); return newArr; } console.log(codeNation([1, 3, 5, 7, 9, 11])); // 输出 [3, 7, 11]
最优实现方法
使用数组的filter方法是更简洁、可读性更高的方案,filter会自动遍历数组并保留符合条件的元素,天然维持原顺序:
function codeNation(arr) { return arr.filter((value, index) => index % 2 !== 0 && value % 2 !== 0); } console.log(codeNation([1, 3, 5, 7, 9, 11])); // 输出 [3, 7, 11]
逻辑说明
- 数组索引从0开始,奇数索引即
index % 2 !== 0(对应位置1、3、5...) - 元素为奇数的判断条件是
value % 2 !== 0 - 两个条件需要同时满足,用逻辑与
&&连接 filter方法返回新数组,不会修改原数组,符合函数式编程的最佳实践
内容的提问来源于stack exchange,提问作者SarahCodes
相关产品推荐
相关产品推荐

