编写一个函数,接受两个字符串(a和b)作为参数。返回a出现在b中的次数。
期望输出:
myFunction(‘m’, ‘how many times does the character occur in this sentence?’) => 2
myFunction(‘h’, ‘how many times does the character occur in this sentence?’) => 4
myFunction(‘?’, ‘how many times does the character occur in this sentence?’) => 1
myFunction(‘z’, ‘how many times does the character occur in this sentence?’) => 0
方法一:
funtion MyFunction(a, b) {
return b.split(a).length - 1;
}
方法二:
funtion MyFunction(a, b) {
let num = 0;
Array.from(b).forEach(item => {
if(item === a) num++;
});
return num;
}
方法三:
funtion MyFunction(a, b) {
let num = 0;
for(let i = 0; i < b.length; i++){
if(b[i] === a) num++;
}
return num;
}
方法四:
funtion MyFunction(a, b) {
return b.split('').reduce((prev, cur) => {
if(cur === a) prev++;
return prev
},0)
}