...

View Full Version : newbie. fail to understand dot-notation and arrays



Roy Gardiner
02-12-2004, 11:16 AM
var aa = new Object()
aa[1] = "pqr"
aa[1].b = "xyz"
alert("1aa>" + aa[1].b + "<")
aa.b = "pqr"
alert("2aa>" + aa.b + "<")
The first ALERT gives UNDEFINED. Why? What property, if any, of aa[1] does aa[1].b = "xyz" set?

Garadon
02-12-2004, 11:45 AM
VARNAME[n] <-is for arrays.
[n] indicates what item in a list of items u want, n being the index in the list.

VARNAME.XXXX <- is for objects.
.XXXX indicates what function/variable in a box full of functions/variables u want,XXXX being the name of the function/variable

mordred
02-12-2004, 12:06 PM
No garadon, that is not the reason why the code in question behaves like that. It's because Roy is trying to create a new property on a primitive value. Only objects can have new properties assigned to dynamically. So we can make the code work by changing it slightly:



var aa = new Object()
aa[1] = new String("pqr");
aa[1].b = "xyz"
alert("1aa>" + aa[1].b + "<")
aa.b = "pqr"
alert("2aa>" + aa.b + "<")


Yes, there is a difference between a string and a String object. :)
To show what's going on try to run this code:



var aa = new Object()

aa[1] = "pqr";
alert(typeof aa[1]);

aa[2] = new String("pqr");
alert(typeof aa[2]);


And accessing object properties by using the square bracket notation is perfectly valid and not only reserved to array indices. See also http://www.litotes.demon.co.uk/js_info/sq_brackets.html

Roy Gardiner
02-12-2004, 01:53 PM
Thank you, Mordred, an excellent explanation. I was thrown by thinking that each element of the array was itself an object. Why doesn't the assignment
aa[1].b = "xyz" in the original give an error? Is there any way of ensuring that each array element is always an object without having to say so specifically in the way you demonstrated?

Following dot must be an identifier; inside [] must be a string expression which resolves to an identifier. Are there any other fundamental differences between . and [] I need to know?



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum