0

I have the following code:

var intrebari = new Array();
var i = 0;
intrebari[i]['enunt'] = 'test';
alert(intrebari[i]['enunt']);

The problem is that when I run it it says that intrebari is undefined. Why?

1
  • Note that just [] is the same as "new Array()", and {} is the same as "new Object()". Just to save you some typing :-) Commented Jun 8, 2011 at 11:49

3 Answers 3

2

Yes interbari[0] is null , so it cannot be object - and for adding into array use push instead of indexes

var intrebari = [];
intrebari.push({ 'enunt': 'test' });
alert(intrebari[i]['enunt']);

This will work

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

1 Comment

Alternatively, intrebari[i] could be set to just {}, and then that assignment in the original would work. But this answer is correct.
1
var intrebari = new Array();
var i = 0;
intrebari[i] = new Object()
intrebari[i]['enunt'] = 'test';
alert(intrebari[i]['enunt']);

3 Comments

No, it shouldn't be a new Array; it's being used with a string key, so it should more likely be an object.
@Pointy : fixed it. But is this the only reason of using object instead of array.
Well, arrays have their own behaviors. It works to use an array as an object, because arrays are objects. But there can be strange effects sometimes if the programmer is not very aware of exactly how things work.
1

You need to assign something to intrebari[i] before you can access any properties of it, "by default" its value is undefined that doesn't have any properties. For example:

intrebari[i] = new Object();
intrebari[i]["enunt"] = "test";
alert(intrebari[i]["enunt"]);

Comments

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.