需要检查变量的条件并打印警报

时间:2018-02-28 10:10:13

标签: arrays variables

我想检查条件变量countItems是否等于变量countMatchInput如果它等于那么它应该给出一个警告Hi。变量countItems是一个数组

以下Javascript代码

    var countItems = ["C++", "C#", "VB", "Java and Ruby","Physics", "Chemistry", "Mathematics", "Social Science", "History", "Geography", "Rickshaw", "Bike", "Car", "Bus and Train"];

    function addCounts() {   
    var countMatchInput = document.getElementById("countMatchInput").value;
    document.getElementById("demo").innerHTML = countMatchInput;
    for (var i = 0; i < countItems; i++) {
      if(countItems === countMatchInput)
      {
          alert("Hi");
      }
  }
};

Html代码在

之下
 <textarea id="countMatchInput"></textarea>
          <button onclick="addCounts()">
            Add
          </button>
        <p id="demo">
        </p>

1 个答案:

答案 0 :(得分:1)

您的for循环错误:

var countItems = ["C++", "C#", "VB", "Java and Ruby","Physics", "Chemistry", "Mathematics", "Social Science", "History", "Geography", "Rickshaw", "Bike", "Car", "Bus and Train"];

function addCounts() {   
    var countMatchInput = document.getElementById("countMatchInput").value;
    document.getElementById("demo").innerHTML = countMatchInput;
    for (var i = 0; i < countItems.length; i++) {
        if(countItems[i] === countMatchInput){
            alert("Hi");
        }
  }
};