重复循环结果

时间:2018-12-05 15:53:40

标签: javascript html

我的代码有什么问题:

function Nums( use, dep, unt, prt, no){
      this.uses = use;
      this.department = dep;
      this.units = unt;
      this.part = prt;
      this.numbers = no;
    }

      var n1 = new Nums( "use1", "depart1", "unit1", "part1", "3562")
      var n2 = new Nums( "use2", "depart2", "unit2", "part2", "5226" )

      var obj = [n1, n2];
      var res = [];
      var r = "";
      var srch = "5"
      var div = document.getElementById("a");

      for( i = 0; i<obj.length; i++){
        for( key in obj[i]){
          if(obj[i][key].includes(srch)){
            res.push(obj[i])
            for( x = 0; x<res.length; x++){
              for( itm in res[x]){
                res2 = r += res[x][itm]
                div.innerHTML = res2;
              }
            }
          }
        }
      }
      console.log(res)

我想在innerhtml中打印结果,但输出在“ html” console 内部重复两次,结果是正确的。 是什么原因?

innerHTML结果:

  

use1 => depart1 => unit1 => part1 => 3562 => use1 => depart1 => unit1 => part1 => 3562 => use2 => depart2 => unit2 => part2 => 5226 =>

控制台结果:

  

[{uses:“ use1”,部门:“ depart1”,单位:“ unit1”,部分:“ part1”,数字:“ 3562”},   {uses:“ use2”,部门:“ depart2”,单位:“ unit2”,部件:“ part2”,编号:“ 5226”}]

See the code

1 个答案:

答案 0 :(得分:0)

您在每次迭代时都在res数组上循环并保持追加。

  for( i = 0; i<obj.length; i++){
    for( key in obj[i]){
      if(obj[i][key].includes(srch)){
        res.push(obj[i])
        for( x = 0; x<res.length; x++){
          for( itm in res[x]){
            res2 = r += res[x][itm]
            div.innerHTML = res2;
          }
        }
      }
    }
  }

它需要移出或仅循环到刚添加的最后一个。

for (let i = 0; i<obj.length; i++) {
  for (let key in obj[i]){
    if(obj[i][key].includes(srch)) {
      res.push(obj[i])
    }
  }
}
for (let x = 0; x<res.length; x++) {  //pull out of the loops above
  for(let itm in res[x]) {
    res2 = r += res[x][itm]
  }
}
div.innerHTML = res2;  // only update DOM when done

并确保您声明了变量,并且创建了很多全局变量。