----关于统计字符出现次数的JS循环以及indesxOf函数----
以下将会通过JS循环判断字符“banana”出现次数
以及调用indexOf中的函数来实现统计
<!DOCTYPE html>
<html>
<body>
<p id="p1">apple banana orange banana apple orange banana</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "apple banana orange banana apple orange banana";
var pos = str.indexOf("banana");
var time = 0;
var sp = str.indexOf("banana");
while (sp != -1) {
sp = str.indexOf("banana", sp);
if (sp != -1) {
time++;
sp++;
}
}
document.getElementById("demo").innerHTML = pos;
document.getElementById("demo").innerHTML = time;
}
</script>
</body>
</html>