重用简单的Javascript函数

时间:2014-03-30 20:03:19

标签: javascript

我是JS的新手,想知道如何重构这个简单的代码,以便我可以传入字符串来计算字符串中“e”的数量。

function countE() {
  var count = 0;
  var str = "eee";
  var charLength = str.length;

  for (i =0; i <= charLength; i++){
      if(str.charAt(i) == "e"){
          count++;
      }
  }
   console.log(count);
}

我想执行此功能,我可以执行以下操作:

countE('excellent elephants');

会记录5。

4 个答案:

答案 0 :(得分:2)

function countE(str) {
  if(typeof(str)==='undefined') str = 'eee';
  var count = 0;
  var charLength = str.length;

  for (i =0; i <= charLength; i++){
      if(str.charAt(i) == "e"){
          count++;
      }
  }
  console.log(count);
}

答案 1 :(得分:1)

如果您想缩短功能体,可以执行以下操作:

function countE(str) { 
    return str.match(/e/g).length; 
}

更复杂:

function count(what) {
    return function(str) {
        return str.match(new RegExp(what, 'g')).length;
    };
}

// now you can do the this
var countE = count('e');
var resultE = countE('excellent elephants');

var countL = count('l');
var resultL = countL('excellent elephants');

答案 2 :(得分:0)

如果我理解你的评论,你想做这样的事情:

function countE(inString) {
  var count = 0;
  var str = inString ? inString : "eee";
  var charLength = str.length;

  for (i =0; i <= charLength; i++){
      if(str.charAt(i) == "e"){
          count++;
      }
  }
   console.log(count);
}

答案 3 :(得分:0)

您还可以使用正则表达式

function countE(str) {
   var count = str.match(/e/g).length;
   console.log(count);
}

function countE(str) {
   console.log(str.match(/e/g).length);
}