0
function test() { var test_array = []; } var arrayList = new Array(); arrayList[0] = new test(); arrayList[0].test_array[0] = "test"; 

(try it out)

I'm trying to create an array, initialize an object as a member of that array, and then assign a text value to an array inside that object. However the array inside the object gives

TypeError: arrayList[0].test_array is undefined 

when I try to assign a string to the inner array. I'm still pretty new to javascript so any tips to best practice in this case would be greatly appreciated.

2

3 Answers 3

4

Statement var test_array = []; creates a local variable which will not be visible outside the scope it is defined within. What you need here is the variable defined as the property of object instance. Use this reference inside your test function:

function test() { this.test_array = []; } 

For more information on scopes in JavaScript read the documentation.

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

3 Comments

When I make this change the I get SyntaxError: missing variable name jsfiddle.net/5t62z/4
@WilliamMartin: There's no syntax error in this answer. Read and type carefully and double check your work. You're doing var this.test_array = [];, which isn't valid.
@WilliamMartin strange, I've modified your fiddle as I've described and printed the value of arrayList[0].test_array[0] via console.log(arrayList[0].test_array[0]) - it worked as expected.
2

var declarations within a constructor don't actually modify the instance. They're just locally-scoped within the constructor function itself.

To define a property of the instance, you have to modify this:

function test() { this.test_array = []; } 

Comments

1

Updated Fiddle: http://jsfiddle.net/5t62z/3/

Your function was not returning anything. If you notice my update, I now will return an object with the test_array property.

function test() { return { test_array: [] }; } 

1 Comment

"Your function was not returning anything..." Yes it does. It returns a new object because it was invoked using new. jsfiddle.net/5t62z/5

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.