【问题标题】:How to stop javascript loop once match is found in array一旦在数组中找到匹配项,如何停止javascript循环
【发布时间】:2016-02-25 18:16:24
【问题描述】:

我尝试找到一些修复程序,但似乎没有找到我正在寻找的东西。也许是我的措辞。

所以我有这个表单,一旦它使用 5 位邮政编码提交,它会检查一个数组是否匹配值,一旦它匹配我希望它显示成功消息,如果它不匹配则返回不匹配,但目前它返回消息的次数与数组一样多。我对 JavaScript 还是很陌生,所以任何帮助都将不胜感激。提前致谢!

JavaScript:

<script>
function getZip(e) {
    e.preventDefault();
    var zip = document.getElementById('zip').value; // Gets the value from the text field "zip" on the form.
    var result = ["48650", "48611", "48746", "48614", "48706"];

    for (var i = 0; i < result.length; i++) {
        //console.log(result[i]);

        //if (zip.length == 5 && zip == result[i]){
        if (zip == result[i]) {
            console.log(zip + " is = to " + result[i]);
            alert('Match ' + zip);

        } else if (result[i] != zip) {
            alert("No Match1");
            console.log(zip + " is != to " + result[i]);

        } else {
            alert("No Match2");
            console.log(zip + " is != to " + result[i]);
        }
        //return false;
    }
    if (zip === "") { // Checks if the text field "zip" is empty, if so it returns an error message.
        alert('Please enter a zip code!');

    } else if (zip.length > 5) {
        alert("Please enter a valid 5 digit numeric zip code.");

    } else if (zip.length < 5) {
        alert("Please enter a valid 5 digit numeric zip code.");

    } else if (isNaN(zip)) { // Checks if the text field "zip" for alphabetic characters. The "isNaN" function is to determine if a value does not convert to a number, if so it returns an error message.
        alert("Please enter a numeric value.");
    }
}
</script>

表格:

<div class="searchZip">
    <p>Please enter your zip code for availability</p>
    <form>
        <input type="text" name="zip" id="zip" placeholder="Zip Code">
        <button onclick="getZip(event);">Check</button>
    </form>
    <p id="display"></p>
</div>

【问题讨论】:

标签: javascript arrays json loops for-loop


【解决方案1】:

正如其他人所说,您可以使用break 退出循环。

虽然我不会使用循环。相反,我会使用.some 函数来确定是否匹配:

function getZip(e) {
  e.preventDefault();
  var zip = document.getElementById('zip').value; // Gets the value from the text field "zip" on the form.
  var result = ["48650", "48611", "48746", "48614", "48706"];

  if (zip === "") { // Checks if the text field "zip" is empty, if so it returns an error message.
    alert('Please enter a zip code!');

  } else if (zip.length > 5) {
    alert("Please enter a valid 5 digit numeric zip code.");

  } else if (zip.length < 5) {
    alert("Please enter a valid 5 digit numeric zip code.");

  } else if (isNaN(zip)) { // Checks if the text field "zip" for alphabetic characters. The "isNaN" function is to determine if a value does not convert to a number, if so it returns an error message. 
    alert("Please enter a numeric value.");
  } else {
    var match = result.some(function(r) {
      return zip === r;
    });

    if (match) {
      alert('Match ' + match);
    } else {
      alert("No Match");
    }
  }
}
<div class="searchZip">
  <p>Please enter your zip code for availability</p>
  <form>
    <input type="text" name="zip" id="zip" placeholder="Zip Code">
    <button onclick="getZip(event);">Check</button>
  </form>
  <p id="display"></p>
</div>

或者,您可以使用 indexOf 进行像您这样的简单匹配。

【讨论】:

    【解决方案2】:

    使用break 跳出循环。

    在您的情况下,不需要for,使用Array#indexOf 来检查数组是否包含元素。

    您还可以将 HTML5 pattern 属性与正则表达式 [1-9][0-9]{4} 一起使用。

    var result = ["48650", "48611", "48746", "48614", "48706"],
      display = document.getElementById('display');
    
    function getZip(e) {
      e.preventDefault();
      var zip = document.getElementById('zip').value,
        message = '',
        className = 'valid';
    
      // Remove classes
      display.classList.remove('valid')
      display.classList.remove('invalid');
    
      // Check if entered valid zipcode
      if (/^[1-9][0-9]{4}$/.test(zip) === false) {
        message = 'Please enter valid 5 digit zip code';
        className = 'invalid';
      } else {
        var index = result.indexOf(zip);
    
        if (index > -1) {
          message = 'Zip ' + zip + ' found at index ' + index;
        } else {
          message = 'Zip not found in array';
        }
      }
    
      // Show message
      display.innerHTML = message;
      display.classList.add(className);
    }
    #zip:invalid,
    .invalid {
      color: red;
    }
    .valid {
      color: green;
    }
    <div class="searchZip">
      <p>Please enter your zip code for availability</p>
      <form>
        <input type="text" name="zip" id="zip" placeholder="Zip Code" pattern="[1-9][0-9]{4}">
        <button onclick="getZip(event);">Check</button>
      </form>
      <p id="display"></p>
    </div>

    【讨论】:

    • 所以如果我把它放在这里,这应该可以吗? } else if (result[i] != zip) { alert("No Match1"); console.log(zip + " is != to " + result[i]);休息;
    • @DallasClymer 如果将break 放入循环中,控件将被抛出for 之外,其余代码将被执行
    • 虽然我们使用的是pattern 属性,但if (zip.length.. 也可以替换为required 属性。
    • @Abhitalks 在 JS 中? required 只会检查任何值,这里 OP 想要一个 5 位,所以添加它。
    • 哦,是的@Tushar。我的错,忽略了这一点。
    【解决方案3】:

    将break放入条件分支体

    function getZip(e){
    e.preventDefault();
    var zip = document.getElementById('zip').value; // Gets the value from the text field "zip" on the form.
    var result = ["48650","48611","48746","48614","48706"];
    
      for (var i=0; i<result.length; i++){
        //console.log(result[i]);
    
          //if (zip.length == 5 && zip == result[i]){
            if (zip == result[i]){
              console.log(zip + " is = to " + result[i]);
              alert('Match ' + zip);
              break;
    
            } else if (result[i] != zip) {
            alert("No Match1");
            console.log(zip + " is != to " + result[i]);
              break;
    
            } else {
            alert("No Match2");
            console.log(zip + " is != to " + result[i]);
              break;
          }
            //return false;
      }
      if (zip === "") { // Checks if the text field "zip" is empty, if so it returns an error message.
        alert('Please enter a zip code!');
    
      } else if (zip.length > 5) {
        alert("Please enter a valid 5 digit numeric zip code.");
    
      } else if (zip.length < 5) {
        alert("Please enter a valid 5 digit numeric zip code.");
    
      } else if (isNaN(zip))  { // Checks if the text field "zip" for alphabetic characters. The "isNaN" function is to determine if a value does not convert to a number, if so it returns an error message. 
        alert("Please enter a numeric value.");
      }
    }
    <div class="searchZip">
      <p>Please enter your zip code for availability</p>
         <form>
            <input type="text" name="zip" id="zip" placeholder="Zip Code">
               <button onclick="getZip(event);">Check</button>
         </form>
         <p id="display"></p>
    </div>

    【讨论】:

    • 中断仅用于显示数组中的第一个匹配项,其余部分显示为 false,因为它没有循环遍历其余部分。
    【解决方案4】:

    算法可以更简单

    function getZip(e){
    e.preventDefault();
    var zip = document.getElementById('zip').value; // Gets the value from the text field "zip" on the form.
    var result = ["48650","48611","48746","48614","48706"];
    
            if (result.indexOf(zip) === -1){
              alert("No Match1");
            } else {
              alert('Match ' + zip);
            }
       
      if (zip === "") { // Checks if the text field "zip" is empty, if so it returns an error message.
        alert('Please enter a zip code!');
    
      } else if (zip.length > 5) {
        alert("Please enter a valid 5 digit numeric zip code.");
    
      } else if (zip.length < 5) {
        alert("Please enter a valid 5 digit numeric zip code.");
    
      } else if (isNaN(zip))  { // Checks if the text field "zip" for alphabetic characters. The "isNaN" function is to determine if a value does not convert to a number, if so it returns an error message. 
        alert("Please enter a numeric value.");
      }
    }
    <div class="searchZip">
      <p>Please enter your zip code for availability</p>
         <form>
            <input type="text" name="zip" id="zip" placeholder="Zip Code">
               <button onclick="getZip(event);">Check</button>
         </form>
         <p id="display"></p>
    </div>

    【讨论】:

    • 这样就简单了,请问if (result.indexOf(zip) === -1){ 是什么意思?
    • indexOf 返回数组中值的索引。如果未找到该值,则返回 -1。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 2014-08-21
    • 1970-01-01
    • 2021-07-26
    相关资源
    最近更新 更多