问题:字符e
在字符串 str
出现的次数和位置
var str = 'To be, or not to be, that is the question.';
var count = 0; // 出现的次数
var countArr = []; // 出现的位置
字符串方式实现
ndexOf() 方法返回调用 String 对象中第一次出现的指定值的索引,开始在 fromIndex进行搜索。
var position = str.indexOf('e');
while (position >= 0) {
count++;
countArr.push(position);
position = str.indexOf('e', position + 1);
}
答案:
console.log('出现的次数', count); // displays 4
console.log('出现的位置', countArr); // displays [4, 18, 31, 35]
例子:
"Blue Whale".indexOf("Blue"); // returns 0
"Blue Whale".indexOf("Blute"); // returns -1
"Blue Whale".indexOf("Whale", 0); // returns 5
"Blue Whale".indexOf("Whale", 5); // returns 5
"Blue Whale".indexOf("", 9); // returns 9
"Blue Whale".indexOf("", 10); // returns 10
"Blue Whale".indexOf("", 11); // returns 10
字符串方式详情参见:String.prototype.indexOf()
更新于 2018年2月7日13:47:49
数组方式实现
IE >= 9
str.split('').forEach((item, index) => {
if (item === 'e') {
count++;
countArr.push(index);
}
});
console.log('出现的次数', count); // displays 4
console.log('出现的位置', countArr); // displays [4, 18, 31, 35]
// reduce方式实现
count = str.split('').reduce((total, item, index, arr) => {
if (item === 'e') {
countArr.push(index);
return ++total;
} else return total;
}, 0);
console.log('出现的次数', count); // displays 4
console.log('出现的位置', countArr); // displays [4, 18, 31, 35]