案例一、
查找字符串"abcoefoxyozzopp"中所有o出现的位置以及次数
代码如下:
var str = 'abcoefoxyozzopp';
var index = str.indexOf('o');
var num = 0;
while( index !== -1){
console.log(index);
num++;
index = str.indexOf('o',index + 1);
}
console.log(num);
运行结果如下:
案例二、
[‘red’,‘blue’,‘black’,‘red’,‘green’,‘red’],求red出现的位置及次数
代码如下:
var arr = ['red','blue','black','red','green','red'];
var index = arr.indexOf('red');
var num = 0;
while( index !== -1){
console.log(index);
num++;
index = arr.indexOf('red',index + 1);
}
console.log(num);