首页 > 解决方案 > 查找数组中第四次出现的索引号

问题描述

提示是在数组中查找数字第四次出现的索引号。我正在尝试在 for 循环语句中实现 break,我不确定如何使其工作。这是我的代码:

let array = [0,4,4,3,2,1,4,5,6,4,6,9];

for (i = 0; i <= array.length; i++){
    if (array[i] === 4){
        console.log("The fourth occurrence of 4 is:", i)
        break;
    }
}

假设输出

The fourth occurrence of 4 is: 9

标签: javascript

解决方案


这将为您解决问题:

function getFourthOccurance(number){
    let ocurrences = 0;
    for (i = 0; i <= array.length; i++){
        if (array[i] === number){
            ocurrences++;
            if(ocurrences === 4){
                return i;
            }
        }
    }
}

let array = [0,4,4,3,2,1,4,5,6,4,6,9];
console.log("The fourth occurrence of 4 is:", getOccurance(4))

推荐阅读