【发布时间】:2017-03-31 01:06:09
【问题描述】:
我已经尝试自学 ES6 有一段时间了。这是我学到的一个小例子,比如 let、const 和 => 函数。有没有更优雅或更短的方法来写这个?也许用forEach替换for循环?欢迎任何提示和帮助。
'use strict';
const countChar = (string, ch) => {
let counted = 0;
for (let i = 0; i < string.length; i++) {
if (string.charAt(i) === ch) {
counted += 1;
}
}
return counted;
};
const countBs = string => countChar(string, 'B');
console.log(countBs('BBC'));
console.log(countChar('kakkerlak', 'k'));
【问题讨论】:
标签: javascript optimization ecmascript-6