Claim:
Given a string oabcoefoxyozzopp
, it is required to output o
the position and number of occurrences of the character .
Realization ideas:
- Find the first
o
occurrence - Then as long as the
indexOf
returned result is judged , if it is not -1, then continue to search - Because
indexOf
only the first one can be found, the subsequent search uses the second parameter to add 1, to the current indexstr.indexOf('o', index + 1)
, to continue the search
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
var str = "oabcoefoxyozzopp";
var index = str.indexOf('o');
// 先找到第一个o的位置,幅值给index
var num = 0;
// num表示o出现的次数
while (index !== -1) {
// 如果index不等于-1表示还没查找完,则继续查找
// 若index等于-1,则表示当前索位置之后没有o了,退出循环
console.log(index);
// 输出当前的位置
num++;
index = str.indexOf('o', index + 1);
// 在当前的索引位置+1,重新赋值给index,从后一个位置继续查找
}
console.log('“o”出现的次数是: ' + num);
</script>
</body>
</html>