【问题标题】:Is there a way to write this small piece of code in a more elegant, optimized way? (ES6)有没有办法以更优雅、更优化的方式编写这段代码? (ES6)
【发布时间】: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


    【解决方案1】:

    优雅在旁观者的眼中,但这里有一种方法可以通过使用reduce 来进一步降低它:

    'use strict';
    
    const countChar = (string, ch) => 
      string.split('').reduce((sum, c) => sum + (c === ch), 0);
    
    const countBs = string => countChar(string, 'B');
    
    console.log(countBs('BBC'));
    console.log(countChar('kakkerlak', 'k'));

    它的工作原理是将字符串转换为字符数组,然后将该数组中匹配ch 的字符数相加。我还(ab)使用true转换为1false转换为0的事实,因此将c === ch添加到运行总和将添加1如果匹配,则添加0不。

    【讨论】:

    • 我认为与其滥用true 转换为1false 转换为0 的事实,您应该这样做:(c === ch ? 1 : 0)
    • @Gothdo 你可以。我更喜欢这种情况下的滥用,因为我只是想让它更紧凑。对我来说,它读起来也很好。 “如果字符匹配,则添加另一个。”
    【解决方案2】:

    不一定与 ES6 相关,而是一种更实用的方法,例如在这里使用filter() 看起来不错:

    const countChar = (string, needle) =>
      string.split('')
        .filter(char => char === needle)
        .length;
    
    const countBs = string => countChar(string, 'B');
    
    console.log(countBs('BBC'));
    console.log(countChar('kakkerlak', 'k'));

    【讨论】:

      【解决方案3】:

      你考虑过regular expressions吗?

      alert('kakkerlak'.match(/k/g).length)

      【讨论】:

      • 王冠。
      • string.match(new RegExp(ch,'g')).length
      • 这是非常短的 xD 我认为没有人会比这更短,但我以前从未使用过正则表达式,所以这对我来说不是最友好的方法。但我肯定会查看正则表达式以获取有关此主题的更多信息。
      • 其实string.split(ch).length-1要短14个字节
      【解决方案4】:

      这是另一种缩短它的方法

      'use strict';
      const countChar = (string, ch) => string.split(ch).length - 1;
      const countBs = string => countChar(string, 'B');
      
      console.log(countBs('BBC'));
      console.log(countChar('kakkerlak', 'k'));

      【讨论】:

      • 这确实短了很多,原版比我的版本长得多,而你的比我的短得多。我喜欢这个,我也喜欢我永远不应该想出这样的事情。如果你正在构建这样的东西,你应该使用你的解决方案吗?
      • 当然,我在生产代码中使用它没有问题,事实上我一直以类似的方式使用split
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-31
      相关资源
      最近更新 更多