javascript - 查找数组中第四次出现的索引号
问题描述
提示是在数组中查找数字第四次出现的索引号。我正在尝试在 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
解决方案
这将为您解决问题:
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))
推荐阅读
- postgresql - 如何确定上次使用索引的时间?
- sparql - Visual Graph 中的意外行为,以及使用 SPARQL 返回三元组时
- r - R中逻辑回归建模中的子集
- sql - 如何在 ORACLE Select 语句中使用条件将单个记录行转换为列
- javascript - 使用 OpenWeatherMap 获取问题
- java - 为什么这里有数组索引越界错误?
- python - Pandas 将季度数据重新采样为组内的月度数据
- python - 如何在 Python 中将对象大小(10,2)的数组制作成二维浮点数组(10,2)
- c++ - 从函数参数中推导 C++ 函数模板类型失败
- html - css 选择器如何重用于多个 html 页面?