今天自己用 split()方法实现了统计某字符在字符串中出现的次数,顺便又百度了一下,看看有没有其它方法,结果看到下面这段函数,但其中的count++; offset += subStr.length;有点看不明白是什么意思,请路过的前辈解惑!function countInstances (mainStr, subStr) { var count = 0; var offset = 0; do{ offset = mainStr.indexOf(subStr, offset); // 通过indexOf获得某字符在字符串中出现的位置 if( offset != -1 ) { // 如果某字符存在于字符串中 count++; offset += subStr.length; } } while ( offset != -1 ); return count;}countInstances('www.segmentfault.com', '.')// alert( countInstances('www.segmentfault.com', '.') );
添加回答
举报
0/150
提交
取消