将循环的每个迭代保存在新变量中

时间:2018-12-12 10:13:18

标签: javascript

我有几个对象的代码。

foreignKeys = {
    @ForeignKey(
            entity = BIN.class,
            parentColumns = {"id"},
            childColumns = {"bin_id"}
    ),
    @ForeignKey(
            entity = ORDER.class,
            parentColumns = {"id}
            childColumns = {"order_id"}
    )},

我想在对象中搜索关键字,例如“ 5”。

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" )

但是我想将每个对象保存在一个新变量中。 然后在html标签中打印变量。

 var obj = [n1, n2],
     res = [],
     srch = "5"
for( i = 0; i<obj.length; i++){
    for( key in obj[i]){
      if(obj[i][key].includes(srch)){
        res.push(obj[i])
         }
       }
     }

怎么写?

see code

1 个答案:

答案 0 :(得分:0)

我在这篇文章中找到了答案:JavaScript: Dynamically Creating Variables for Loops

我需要为每次迭代创建新变量。然后我的代码变成...:

for( x = 0; x < res.length; x++){
         var results = [];
         for( itm in res[x]){           
           if(result[x] == undefined){
             result[x] = "";
           }
           result[x] +=  res[x][itm] ; 

         }
         out += "<p>" + result[x] + "</p>";
       }


document.innerHTML = out ;