查找字符串中某个字符出现的次数

 var str = "abcoefoxyozzopp";    //声明字符串
        var index = str.indexOf('o');    // o 出现的索引号
        var num = 0;  //计数器
        while (index !== -1) {
    
        //index 不等于 -1 执行以下操作
            console.log(index);//打印索引号
            num++; //次数
            index = str.indexOf('o', index + 1);  // o的索引号是 3   + 1 开始往下查找
        }
        console.log('o出现的次数是:' + num);```

猜你喜欢

转载自blog.csdn.net/llt299022/article/details/113603265