I am having a small issue with variable assignment. For some reason my line variable doesn't properly assign.
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);
asked Dec 24, 2011 at 22:15
user1052933
1912 gold badges4 silver badges8 bronze badges
3 Answers 3
Don't use an array for non-integer indexing. Use an object. Also, it's generally better to use [] instead of new Array(). Oh yeah, and there's a line missing a semicolon.
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);
Even more concise:
var records = [];
var recid = -5;
var subrecid = 6495;
var line = {
recid: recid,
subrecid: subrecid
};
if (subrecid) records.push(line);
answered Dec 24, 2011 at 22:19
Matt Ball
361k102 gold badges655 silver badges725 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
RobG
Ha! You did that while I was typing. I considered the different test but it's not clear whether or how subrecid is being modified so it might become -ve at some point.
Matt's answer is fine, but you could take greater advantage of object literal syntax:
var records = [];
var line = {recid: -5, subrecid: 6495 };
if (line.subrecid > 0) records.push(line);
answered Dec 24, 2011 at 22:29
RobG
148k32 gold badges180 silver badges216 bronze badges
1 Comment
Jason Sundram
or for maximum terseness:
var records = [{recid: -5, subrecid: 6495 }];var val1=$('#Accountstype_account_c').val();
Kirsteins
27.3k8 gold badges79 silver badges78 bronze badges
1 Comment
Trisha
It would be helpful to add a bit more explanation as to why this is a solution.
lang-js
var line = {}; line.recid = recid; line.subrecid = subrecid;instead.