如何在 Javascript 中创建数组

How to create array in Javascript?

本文关键字:创建 数组 Javascript      更新时间:2023-09-26

我遇到过我想从数组中的查询输出两个表列的情况。理想情况下,我想输出一个ID_1然后是第二个ID_2,在将所有 ID 存储在数组中后,我想遍历该数组以检查ID_1是否大于 0,如果是,我想使用匹配ID_2来隐藏元素。这是我到目前为止的代码:

var records = [];
~[tlist_sql;
  SELECT ID_1, ID_2 
  FROM SLOTS
  ]
 records.push("~(ID_1)","~(ID_2)");
[/tlist_sql]
for(var i=0; i< records.length; i++){
    //if ID_2 is greater than 0 
    if(records[i].idTwo > 0){
        var test = ('#row_' + records[i].idOne).val();  
                alert(test)
        //here I want to use ID_1 to hide row 
        $j('#row_' + records[i].idOne).parent('.hideElement').hide();
        $j('#button1').hide();
    }       
}

以下是我的数组记录的样子:

[-1,2050,-1,2046,15,2048,0,2044,10,2051,0,2047]

因此,正如您在此数组中看到的,只有两条记录将传递 if 语句,其中 ID_1 为 15,10,ID_2为 2048,2051。我当前的代码没有使用正确的值,看起来像 id 以某种方式被拆分。有谁知道我应该如何寻找ID_1然后寻找ID_2,在这种情况下最好使用数组吗?谢谢。

也许是这样的:

var records = [];
~[tlist_sql;
SELECT ID_1, ID_2 
FROM SLOTS
]
records.push({
   'idOne' : "~(ID_1)",
   'idTwo' : "~(ID_2)"
});
[/tlist_sql]

然后在访问这些记录时:

for(var i=0; i< records.length; i++){
    //if ID_1 is greater than 0 
    if(records[i].idOne > 0){
        //here I want to use ID_2 to hide row that has matching ID
        $j('#row_' + records[i].idTwo).parent('.hideElement').hide();
        $j('#button1').hide();
    }       
}

创建一个对象:

var records = [];
~[tlist_sql;
  SELECT ID_1, ID_2 
  FROM SLOTS
  ]
 records.push({id1:":~(ID_1)",id2:"~(ID_2)"});
[/tlist_sql]
for(var i=0; i< records.length; i++){
    //if ID_1 is greater than 0 
    if(records[i].id1 > 0){
        //here I want to use ID_2 to hide row that has matching ID
        $j('#row_' + records[i].id2).parent('.hideElement').hide();
        $j('#button1').hide();
    }       
}

https://jsfiddle.net/78s3uL95/