如何解决这个“如果”的说法

时间:2019-04-29 02:13:19

标签: javascript

我真的不知道该if语句的正确格式。我希望它计算出txt文件中每个单词的使用频率。

function countWords(array, word, index) {
  var count = 0;
  var value = " "
  for (var i = 0; i < array.length; i++) {
    if (array[i] == 0 && value == word)
      count++;
  }
}



if (getUserSelectionForm.problem.value == "pay") {
  countWords(working2DArray, "pay", 0)
  if (getUserSelectionForm.problem.value == "staffing") {
    countWords(working2DArray, "staffing", 0)
    if (getUserSelectionForm.problem.value == "hours") {
      countWords(working2DArray, "hours", 0)
      if (getUserSelectionForm.problem.value == "management") {
        countWords(working2DArray, "management", 0)
        console.log(countWords)
        document.getElementById('section2').innerHTML = "The selected word      appears " + countWords + " times in the array."
      }

3 个答案:

答案 0 :(得分:2)

尽量不要使用多个IF语句,而应使用switch语句。使代码更清晰,更干净。

例如

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
} 

请参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

所以:

var p = getUserSelectionForm.problem.value;

switch (p) {
    case 'pay':
        countWords(working2DArray, "pay", 0);
        break;
    case 'staffing':
        countWords(working2DArray, "staffing", 0);
}

答案 1 :(得分:0)

您在代码中犯了三个错误:

  • 如果缺少,您可能会错过}上的一些大括号。
  • 您不会{@ 1}从功能中获得任何收益。您应该返回return
  • count是您不需要显示的功能。您需要显示其结果。

您可以使代码更简单。您根本不需要这些countWords语句,因为您要将if的相同值传递给该函数,因此直接将其传递。

getUserSelectionForm.problem.value

如果您只想检查少量项目,请使用创建function countWords(array, word, index) { var count = 0; var value= " " for(var i = 0; i < array.length; i++){ if(array[i] == 0 && value == word) count++; } return count; } let word = getUserSelectionForm.problem.value document.getElementById('section2').innerHTML = `The selected word appears ${countWords(working2DArray,word,0)} times in array` 的数组并在其上使用"pay","staffing"...

includes()

答案 2 :(得分:0)

据我了解,您希望在出现问题时触发该函数。value ==='pay'||'staffing'||'hours'||'management',这里有更清晰的版本供您参考:

var problemValue = getUserSelectionForm.problem.value;
var isProblemValueMatch = ["pay", "staffing" ,"hours", "management"].includes(problemValue);
if (isProblemValueMatch  ) {
  var countWords = working2DArray.filter(function(v) {
    return v === problemValue;
   }).length;
  console.log(countWords)
  document.getElementById('section2').innerHTML = "The selected word appears " + countWords + " times in the array."
}