目录
一、字符串对象
1、根据字符返回位置
方法 |
功能描述 |
---|---|
indexOf(‘a’) |
获取a在字符串中首次出现的位置 |
lastIndexOf(‘a’) |
获取a在字符串中最后出现的位置
|
要求:在一组字符串中,找到所有指定元素出现的位置以及次数
var str = 'Hello World, Hello JavaScript';
var index = str.indexOf('o');
var num = 0;
while (index != -1) {
console.log(index); // 依次输出:4、7、17
index = str.indexOf('o', index + 1);
num++;
}
console.log('o出现的次数是:' + num); // o出现的次数是:3