0

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);
9
  • 2
    Actually, it does. Instead of checking what you think is the solution, can you provide a jsFiddle showing the error? Commented Dec 24, 2011 at 22:17
  • 2
    How do you know it doesn't "assign"? What result are you expecting to get that you aren't getting? Commented Dec 24, 2011 at 22:17
  • 1
    mind you that javascript does NOT have associative arrays. You can use the 1line['syntax'] because you are actually calling an object there, but there is associative array in javascript. It might be the fact you just init it as an array? Commented Dec 24, 2011 at 22:20
  • JavaScript doesn't need arrays for that, by the way; there's no such thing as a hash or associative array. You can use var line = {}; line.recid = recid; line.subrecid = subrecid; instead. Commented Dec 24, 2011 at 22:22
  • 1
    @MДΓΓБДLL: Yeah, it depends on your definition. Commented Dec 24, 2011 at 22:35

3 Answers 3

4

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);
Sign up to request clarification or add additional context in comments.

1 Comment

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.
2

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

1 Comment

or for maximum terseness: var records = [{recid: -5, subrecid: 6495 }];
-1
var val1=$('#Accountstype_account_c').val();

1 Comment

It would be helpful to add a bit more explanation as to why this is a solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.