在Javascript中分配数组变量

时间:2011-12-24 22:15:57

标签: javascript arrays

我在变量赋值方面遇到了一个小问题。由于某种原因,我的行变量没有正确分配。

var records = new Array();
var recid = -5
var subrecid = 6495;
var line = new Array();
line['recid'] = recid;
line['subrecid'] = subrecid;
if (subrecid > 0) records.push(line);

2 个答案:

答案 0 :(得分:4)

不要使用数组进行非整数索引。使用对象。此外,使用[]代替new Array()通常会更好。哦,是的,还有一行缺少分号。

var records = [];
var recid = -5;
var subrecid = 6495;
var line = {}; // object, not array
line.recid = recid;
line.subrecid = subrecid;
if (subrecid > 0) records.push(line);

更简洁:

var records = [];
var recid = -5;
var subrecid = 6495;
var line = {
    recid: recid,
    subrecid: subrecid
};
if (subrecid) records.push(line);

答案 1 :(得分:2)

Matt的答案很好,但您可以更好地利用对象文字语法:

var records = [];
var line = {recid: -5, subrecid: 6495 };

if (line.subrecid > 0) records.push(line);