单击时计算每个单独的元音元素

时间:2017-09-30 15:46:34

标签: javascript html

为我输入句子(字符串)的html文件写一些js。当我点击一个按钮时,它输出每个元音的数量,不包括y而不注意标点符号。我不能使用var所以我试图使用let来完成这项工作。我相信我在正确的道路上,从元音a开始,但如果句子不包含a,我会得到一个错误。我想不出下一步该做什么。有什么想法吗?

'use strict';

let vButton = document.querySelectorAll('#vowels');
vButton.forEach(function(blip) {
  blip.addEventListener('click', function(evt) {
    evt.preventDefault();
    console.log('click');

    let vowelString = document.getElementById('roboInput'),
      sentence = vowelString.value;
    if (sentence !== '') {
      let aMatches = sentence.match(/a/gi).length;
      alert("a - " + aMatches);
    }
    vowelString.value = '';

  });
});
a {
  cursor: pointer;
}

.well-robot {
  min-height: 340px;
}

.input-robot {
  width: 100%;
  min-height: 100px;
}

.output-robot {
  border: 1px solid #000000;
  min-height: 150px;
  margin-top: 10px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
<div class="container">
  <div class="alert alert-info">
    Hello! I'm a smart robot. I can do many interesting things. Type something below and click a button to watch me work!
  </div>
  <div class="row">
    <div class="col-sm-4">
      <img src="./robot.gif">
    </div>
    <div class="col-sm-8 well well-robot">
      <textarea id="roboInput" placeholder="Input something here!" class="input-robot"></textarea>
      <div class="btn-group btn-group-justified">
        <a class="btn btn-default" id="vowels">Count Vowels</a>
        <a class="btn btn-default" id="anagrams">Count Anagrams</a>
        <a class="btn btn-default" id="distance">Word Distance</a>
      </div>
      <div id="robotResult" class="output-robot">
      </div>
    </div>
  </div>
</div>

2 个答案:

答案 0 :(得分:2)

如果正则表达式不匹配,.match()会返回null,而不是空数组,因此您无法获得长度。你需要检查一下。

let matches = sentence.match(/a/gi);
let matchLength = matches ? matches.length : 0;
alert('a - ' + matchLength);

答案 1 :(得分:0)

如果我理解你的问题,你可能需要这样的东西:

&#13;
&#13;
select
&#13;
'use strict';

let vButton = document.querySelectorAll('#vowels');
vButton.forEach(function(blip) {
  blip.addEventListener('click', function(evt) {
    evt.preventDefault();
    //console.log('click');

    let vowelString = document.getElementById('roboInput'),
      sentence = vowelString.value;
    if (sentence) {
      let result = {a: 0, e: 0, i: 0, o: 0, u: 0 };
      for(var i = 0, l = sentence.length; i < l; i++) {
        if(result.hasOwnProperty(sentence[i]))
          result[sentence[i]]++;
      }
      console.log(result);
    }
    
    vowelString.value = '';

  });
});
&#13;
a {
  cursor: pointer;
}

.well-robot {
  min-height: 340px;
}

.input-robot {
  width: 100%;
  min-height: 100px;
}

.output-robot {
  border: 1px solid #000000;
  min-height: 150px;
  margin-top: 10px;
}
&#13;
&#13;
&#13;