5

I have a Javascript object defined as follows:

var active = {
    waypoints: [],
    scenario: []
}

I push to array scenario with:

var myScenario = {
    id:     terrainId,
    text:   text

}; 

active.scenario.push(myScenario);       

However I get 0 when:

console.log(active.scenario.length);

So of course I cannot loop through the array content. If I do:

console.log(active.scenario)

I see the array content within Chrome plus the correct array length. I have similar code that defines and works with arrays, but outside of an object definition.

Most grateful for insight into why length is 0.

2
  • Could you please include a jsFiddle that recreated this behavior? Commented Mar 23, 2014 at 12:11
  • Are you using a vanilla javascript array or are these actually arrays out of a library like Knockout? Commented Mar 23, 2014 at 12:14

1 Answer 1

3

It works fine:

JSFiddle

var terrainId = 1;
var text = "text";

var active = {
    waypoints: [],
    scenario: []
}

var myScenario = {
    id:     terrainId,
    text:   text
}; 

active.scenario.push(myScenario);       

console.log(active.scenario.length);

Looks like the problem is somewhere else.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks san.chez, you were right, problem was timing of an ajax call elsewhere. More specifically, it was the asynchronous handling of the "success" function invocation in my ajax call that sets up the array content. From this I learnt I must become familiar with JSFiddle to set up quick tests myself, thanks again.

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.