如何在JavaScript数组中跳过值为0的元素以获取有效历史分数?
实现逻辑方案
方法一:while循环实现
直接从默认上月索引开始,循环跳过所有0值,直到找到第一个非零值:
const scores = [20, 0, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]; // 固定取当月分数 const currentMonthScore = scores[0]; // 初始化上月分数索引为默认的1 let lastMonthIndex = 1; // 跳过所有连续的0值 while (lastMonthIndex < scores.length && scores[lastMonthIndex] === 0) { lastMonthIndex++; } // 得到最终的上月分数 const lastMonthScore = scores[lastMonthIndex]; console.log(`当月分数:${currentMonthScore}`); console.log(`上月分数:${lastMonthScore}`);
方法二:for循环实现
基于你提供的for循环片段修改,直接从索引1开始遍历,找到非零值就终止循环:
const scores = [20, 0, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]; const currentMonthScore = scores[0]; let lastMonthIndex = 1; // 从索引1开始遍历数组 for (; lastMonthIndex < scores.length; lastMonthIndex++) { // 找到非零值就跳出循环 if (scores[lastMonthIndex] !== 0) { break; } } const lastMonthScore = scores[lastMonthIndex]; console.log(`当月分数:${currentMonthScore}`); console.log(`上月分数:${lastMonthScore}`);
方法三:使用数组findIndex方法(更简洁)
利用数组内置方法直接定位第一个符合条件的索引:
const scores = [20, 0, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]; const currentMonthScore = scores[0]; // 从索引1开始查找第一个非零值的索引 const lastMonthIndex = scores.findIndex((score, index) => index >= 1 && score !== 0); const lastMonthScore = scores[lastMonthIndex]; console.log(`当月分数:${currentMonthScore}`); console.log(`上月分数:${lastMonthScore}`);
补充说明
三种方法核心逻辑一致:默认取索引1的分数,若为0则向后遍历直到找到第一个非零值。如果需要处理索引1之后全为0的极端情况,可以在最后添加判断(比如当lastMonthIndex === scores.length时设置兜底值)。
内容的提问来源于stack exchange,提问作者Florence Adikwu
相关产品推荐
相关产品推荐

