【问题标题】:For loop does not check every object propertyFor 循环不会检查每个对象属性
【发布时间】:2016-11-05 06:15:35
【问题描述】:

我的代码没有检查所有存储对象条形码的问题。我希望它检查所有螺栓、支架、螺丝刀和锤子条码,并用输入一检查,如果相同,则显示相应的对象。但它只适用于最后一个。我不知道是什么原因造成的。行数是有多少输入(您可以单击按钮添加新输入)输入的名称为 input1 input2 input3... 以此类推...

var storage = {
  bolts: {
    barcode: 57263144,
    price: 0.5,
    name: '100mm Bolts',
    stock: 8642,
  },
  brackets: {
    barcode: 13245627,
    price: 0.2,
    name: 'Plain Brackets',
    stock: 5201,
  },
  screwdriver: {
    barcode: 52678349,
    price: 15,
    name: 'Screwdriver',
    stock: 30,
  },
  hammer: {
    barcode: 86583916,
    price: 25,
    name: 'Hammer',
    stock: 5,
  }
}

function check(){
  Object.keys(storage).forEach(function(key) {
    for (var i = 1; i <= rowAmount; i++){

      var barcodeCheck = document.getElementById("input"+i).value;

      var input = document.getElementById("input"+i).value;

      if (input.length > 8){
        document.getElementById("input"+i).style.backgroundColor = "red";
      }
      else {
        document.getElementById("input"+i).style.backgroundColor = "white";
      }


      if (barcodeCheck == storage[key].barcode){
        document.getElementById("name"+i).innerHTML = "Name: "+storage[key].name;
        document.getElementById("price"+i).innerHTML = "Price: £"+storage[key].price+" / one";
        document.getElementById("stock"+i).innerHTML = "In stock: "+storage[key].stock;
      }
      else {
        document.getElementById("name"+i).innerHTML = "";
        document.getElementById("price"+i).innerHTML = "";
        document.getElementById("stock"+i).innerHTML = "";
      }
    }
  });

  setTimeout(check,1);
}
check();

【问题讨论】:

  • 什么是rowAmount,它在哪里定义?
  • rowAmount 是有多少输入(我有一个添加新输入的按钮)每个新输入称为 input1 input2 input3 ...
  • 请附上minimal reproducible example。这个问题的最小部分将包括@Craicerjack 提到的rowAmount,以及代码运行的HTML。附带说明一下,您可以在 1 毫秒内再次调用 check 来关闭您的 check 函数。这可能会导致页面响应能力出现一些严重问题。
  • 如果你愿意,我可以链接你整个代码。
  • 该值无关紧要。如果没有定义 rowAmount 决定了你是否可以回答这个问题,那么我认为你没有理解这个问题。

标签: javascript


【解决方案1】:

我想你要找的是for...in。

你也有这个函数可以经常运行。 1 毫秒的轮询太紧了,你的应用程序的性能会受到影响。

更新:真正的罪魁祸首,正如我所发现的(正如下面的答案所指出的),在您检查了一个键并适当地操作了 DOM 之后,您然后继续检查。随后的检查显然会失败,因为只有一个正确答案,然后一切都会重置。

澄清一下,使用 forEach 遍历键并不是一个错误的解决方案,尽管使用 for...in 更简洁,更适合手头的任务。

var storage = {
  bolts: {
    barcode: 57263144,
    price: 0.5,
    name: '100mm Bolts',
    stock: 8642,
  },
  brackets: {
    barcode: 13245627,
    price: 0.2,
    name: 'Plain Brackets',
    stock: 5201,
  },
  screwdriver: {
    barcode: 52678349,
    price: 15,
    name: 'Screwdriver',
    stock: 30,
  },
  hammer: {
    barcode: 86583916,
    price: 25,
    name: 'Hammer',
    stock: 5,
  }
}

function check(){
  var match = false;

  for (var key in storage) {
    for (var i = 1; i <= rowAmount; i++) {
      //barcodeCheck and input had the same value
      //I also removed the .value. You'll see why in a sec
      var input = document.getElementById("input"+i);

      if (input.value.length > 8) {
        input.style.backgroundColor = "red";
      }
      else {
        input.style.backgroundColor = "white";
      }

      if (input.value == storage[key].barcode){
        document.getElementById("name"+i).innerHTML = "Name: "+storage[key].name;
        document.getElementById("price"+i).innerHTML = "Price: £"+storage[key].price+" / one";
        document.getElementById("stock"+i).innerHTML = "In stock: "+storage[key].stock;

        match = true;
      }
    }

    if (match) break;
  }

  //Only reset if you've checked them all and come up short
  if (!match)
  {
    document.getElementById("name"+i).innerHTML = "";
    document.getElementById("price"+i).innerHTML = "";
    document.getElementById("stock"+i).innerHTML = "";
  }

  //Nobody's going to notice a 250ms delay in your poll
  setTimeout(check, 250);
}
check();

【讨论】:

  • 不起作用,jsfiddle.net/zh2nvkp1 这是我的全部代码,问题是当我输入条形码时,只显示存储中的最后一个(在这种情况下为锤子),其余项目不显示。
  • 哦,我忘了在小提琴中添加 jquery。
  • 已修复。找到匹配项后,您需要结束执行。
  • 我不知道为什么它似乎仍然没有读取其他值。例如,它不读取条形码 13245627,但它应该。
  • 您的小提琴还有其他问题。我正在尝试测试我的解决方案,所以请稍候。
【解决方案2】:

您只看到最后一个是正确的原因是您的 for 循环正在执行每次迭代并检查输入是否与存储的值之一匹配,并且在找到匹配项时不会停止通过 for 循环运行。

function check(){
outer_loop:
Object.keys(storage).forEach(function(key) {
for (var i = 1; i <= rowAmount; i++){

  var barcodeCheck = document.getElementById("input"+i).value;

  var input = document.getElementById("input"+i).value;

  if (input.length > 8){
    document.getElementById("input"+i).style.backgroundColor = "red";
  }
  else {
    document.getElementById("input"+i).style.backgroundColor = "white";
  }


  if (barcodeCheck == storage[key].barcode){
    document.getElementById("name"+i).innerHTML = "Name: "+storage[key].name;
    document.getElementById("price"+i).innerHTML = "Price: £"+storage[key].price+" / one";
    document.getElementById("stock"+i).innerHTML = "In stock: "+storage[key].stock;
break outer_loop; //This will end the for loop and allow the found values to stay instead of over writing them on the next loop iteration and jump out of both loops
  }
  else {
    document.getElementById("name"+i).innerHTML = "";
    document.getElementById("price"+i).innerHTML = "";
    document.getElementById("stock"+i).innerHTML = "";
  }
}
});
 setTimeout(check,1);
}
check();

更新:

下面是固定代码,可以满足您的需求。您首先要查找键,而您应该先查找输入框,然后尝试将它们与键匹配。很抱歉多次更新。

<style>
input {
  float: left;
  border: none;
  border-bottom: 2px solid black;
  outline: none;
  font-size: 24px;
  width: 100%;
  text-align: center;
  transition: width cubic-bezier(0.92,0,0.29,0.99) 0.6s;
  font-family: 'Indie Flower', cursive;
  font-weight: 900;
  clear: both;
}

.red {
  color: red;
}

* {
  font-size: 24px;
  font-weight: 800;
}

#table > div {
  border: 2px solid black;
  float: left;
  width: 300px;
  padding: 5px;
}

input[type=number]::-webkit-inner-spin-button, 
input[type=number]::-webkit-outer-spin-button { 
  -webkit-appearance: none; 
  margin: 0; 
}

.clear {
  clear: both;
}

button {
  background-color: orange;
  border: 2px solid black;
  padding: 14px 16px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.4s;
}
button:hover { 
  border-radius: 10px;
  background-color: yellow;
  transform: translateY(2px);
}


</style>

barcodes: 13245627, 57263144, 52678349, 86583916 <br>
<input type=number id=barcode placeholder=Barcode>
<div id=output></div>
<div id=test></div>
<button onclick=newRow();>New row</button>
<button onclick=deleteRow();>Delete last row</button><br><br>
<div id=table></div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>

<script>
var storage = {
  bolts: {
    barcode: 57263144,
    price: 0.5,
    name: '100mm Bolts',
    stock: 8642,
  },
  brackets: {
    barcode: 13245627,
    price: 0.2,
    name: 'Plain Brackets',
    stock: 5201,
  },
  screwdriver: {
    barcode: 52678349,
    price: 15,
    name: 'Screwdriver',
    stock: 30,
  },
  hammer: {
    barcode: 86583916,
    price: 25,
    name: 'Hammer',
    stock: 5,
  }
}
var rowAmount = 0;

function display(){
  var barcode = document.getElementById("barcode").value;
  var numbers = [];
  var sum = 0;
  for (var i = 0; i < barcode.length; i++){
    numbers[i] = barcode.charAt(i);
    if (i === 0 || i === 2 || i === 4 || i === 6){
      numbers[i] = numbers[i] * 3;
    }
    sum += parseInt(numbers[i]);
  }

  var nearestWhole = Math.ceil(sum/10)*10;

  var lastDigit = (nearestWhole - sum);

  var isRight = false;

  if (barcode.length === 8 && nearestWhole - sum === 0){
    isRight = true;
  }

  document.getElementById("test").innerHTML = numbers+"<br>Sum: "+sum+"        <br>Is right: "+isRight+"<br>Last digit: "+lastDigit+"<br>Nearest whole:     "+nearestWhole;

  if (barcode.length > 8){
document.getElementById("output").innerHTML = "INVALID";
    isRight = false;
  }    
  if (isRight === false && barcode.length > 7){
    document.getElementById("output").innerHTML = "<span class=red>Invalid     barcode</span>"
  }
  else {
    document.getElementById("output").innerHTML = "";
  }

  setTimeout(display,1);
}
display();

function newRow(){
  rowAmount++;
  var elem5 = '<div id=cellNumber'+rowAmount+'>';
  var elem = '<div class=clear></div>';
  var elem1 = '<div id=cell'+rowAmount+'><input type=number placeholder=Barcode id=input'+rowAmount+'></div>';
  var elem2 = '<div id=name'+rowAmount+'></div>';
  var elem3 = '<div id=price'+rowAmount+'></div>';
  var elem4 = '<div id=stock'+rowAmount+'></div>';
  var elem6 = '</div>'
  $('#table').append(elem5+elem+elem1+elem2+elem3+elem4+elem6);
}
function deleteRow(){
  if (rowAmount === 1){
    document.getElementById("input1").value = "";
  }
  if (rowAmount > 1){
    $('#cellNumber'+rowAmount).remove();
    rowAmount--;
  }
}

function check(){


//Object.keys(storage).forEach(function(key) {
outer_loop:
for (var i = 1; i <= rowAmount; i++){
    for(var z=0; z < Object.keys(storage).length;z++){
        var key = Object.keys(storage)[z];

          var barcodeCheck = document.getElementById("input"+i).value;

          var input = document.getElementById("input"+i).value;


          if (input.length > 8){
            document.getElementById("input"+i).style.backgroundColor = "red";
          }
          else {
            document.getElementById("input"+i).style.backgroundColor = "white";
          }


          if (barcodeCheck == storage[key].barcode){
            document.getElementById("name"+i).innerHTML = "Name: "+storage[key].name;
            document.getElementById("price"+i).innerHTML = "Price: £"+storage[key].price+" / one";
            document.getElementById("stock"+i).innerHTML = "In stock: "+storage[key].stock;
            break; //This will end the for loop and allow the found values to stay instead of over writing them on the next loop iteration
      }
      else {
            document.getElementById("name"+i).innerHTML = "";
            document.getElementById("price"+i).innerHTML = "";
            document.getElementById("stock"+i).innerHTML = "";
      }
    }
  }

  //Nobody's going to notice a 250ms delay in your poll
  setTimeout(check, 250);
}
check();

newRow();
</script>

【讨论】:

  • 我也犯了这个错误。此修复仅破坏 ​​inner 循环,因此它会检查下一个键并重置。
  • 啊,我错过了外循环。
  • 我更新了我的答案,将 outer_loop 名称位置包含在您获得所需数据后要中断的位置。
  • 我想通了,else 语句将一切都变回了无。其他一切都很好。谢谢你的尝试。
猜你喜欢
  • 2017-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-27
  • 2016-03-11
  • 1970-01-01
  • 2021-02-27
  • 1970-01-01
相关资源
最近更新 更多