For循环不检查每个对象属性

时间:2016-11-04 20:56:05

标签: javascript

我有一个问题,我的代码没有检查所有存储对象条形码。我想要检查所有螺栓,支架,螺丝刀和锤子条形码,并用输入一检查它,如果它相同则显示相应的对象。但它始终适用于最后一个。我不知道造成这种情况的原因。行数是有多少输入(你可以点击一个按钮添加新的输入)输入有名称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();

2 个答案:

答案 0 :(得分:1)

我认为你要找的是for...in

你也有这个功能可以不断运行。 1ms是一个非常严格的民意调查,你的应用程序的性能将受到影响。

更新:正如我发现的那样(以及下面指出的答案),真正的罪魁祸首是,在检查完密钥并适当操作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();

答案 1 :(得分:0)

您只看到最后一个是正确的原因是您的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>