0

I'm trying to add multiple Objects and later to display them all. How would I do this? Every method I googled just uses For-In/For and iterate through characters and I only see the last added object...

for(var i = 0; i < forms.length; i++) 
{
        alert(forms[i].id + " " + 10 + " " + forms[i].value);
        var aObj = new A(forms[i].id, 10, forms[i].value);
        var obj = JSON.stringify(aObj);
}

var str = "";
for(var i = 0; i < jObj.length; i++) 
{
    str += jObj[i]; 
}

alert(str);

Only solution I can come up is to create an array and store them all there?

3
  • I don't see where you're adding the object into the jObj array. Can you show that as well? Commented Jan 30, 2014 at 22:07
  • I misunderstood your question, HelpNeeder. See edit. Commented Jan 30, 2014 at 22:08
  • 1
    Although you aren't adding them to an array in your code (like @Joel already noted), there's nothing wrong in storind them in an array (i.e. with obj[i] in your code above, just declare obj as an Array outside the first loop). Commented Jan 30, 2014 at 22:08

1 Answer 1

1

You are reinitalizing the variables aObj and obj and that is causing them to be overwritten every time the loop is executed. They should be arrays with the iteration specified.

var aObj;
var obj = [];
var str = "";

for(var i = 0; i < forms.length; i++) 
{
        alert(forms[i].id + " " + 10 + " " + forms[i].value);
        aObj = new A(forms[i].id, 10, forms[i].value);
        obj[i] = JSON.stringify(aObj);
}

for(var i = 0; i < jObj.length; i++) 
{
    str += jObj[i]; 
}

alert(str);
Sign up to request clarification or add additional context in comments.

4 Comments

Ok, so array is its. Ok, but I don't think aObj[] need to be an array.
aObj refers to A (non-default) constructor.
@HelpNeeder you are right, revised. Btw, what is jObj in the second loop? Did you mean obj?
Thats a JSON object which result in stringified output, so I thought. Your answer helps a lot. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.