有没有办法以更优雅,更优化的方式编写这一小段代码? (ES6)

时间:2016-11-16 17:44:20

标签: javascript optimization ecmascript-6

我一直在尝试自学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'));

4 个答案:

答案 0 :(得分:4)

这是缩短它的另一种方法

SELECT  
    Customerid, CustomerName, [ftga.ihs.com] as ftga, [Email Delivery] as Email 
FROM  
    (SELECT 
         Customerid, CustomerName, AliasName, 
         Deliverylocation,FTPUsername,FTPPassword
     FROM
         [dbo].[tblCustomerDeliveryServerMapping] t1
     INNER JOIN
         tblDeliveryServerDetails t2 ON t1.Deliveryserverid = t2.id
     INNER JOIN
         tblcustomerinfo t3 ON t1.customerid = t3.id) AS P
PIVOT 
    (MAX(Deliverylocation + FTPUsername + FTPPassword) 
     FOR AliasName in ([ftga.ihs.com],[Email Delivery])
    ) AS  PVT

答案 1 :(得分:3)

您考虑过regular expressions吗?

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

答案 2 :(得分: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 :(得分:1)

优雅在旁观者的眼中,但通过使用reduce可以进一步减少它:

&#13;
&#13;
'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'));
&#13;
&#13;
&#13;

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