Sample of javascript code:
function a() {
this.array1 = [];
this.addToArray = function(name) {
this.array1.push(new b(name));
return true;
}
this.searchForName = function(name) {
for(var i in this.array1) {
alert(i.name);
}
}
function b(name) {
this.name = name;
}
}
I included this javascript file in an html document. Inside script tags of an html document I have this code:
var myObject = new a();
myObject.addToArray("test1");
myObject.searchForName("test1");
Running this code, I would expect an alert with "test1"
in it to pop up, but instead it pops up as undefined. The debugger in Chrome, however, shows that there is an array inside of myObject with an item 0 that has a name of "test1"
. When I use breakpoints to test the code, it shows that at the moment the alert is called, i.name is undefined. What is wrong with this?
You're looking for the name
property on the i
number instead of in member i
of this.array
.
So:
i.name
should be:
this.array1[i].name
Result is:
this.searchForName = function(name) {
for(var i in this.array1) {
// get it from this array1
alert(this.array1[i].name);
}
}
Working example: http://jsfiddle.net/seNxD/
Also, it is not a good idea to use a for-in
statement if you're only interested in numeric indices. A for
statement is the one to use since you're not enumerating.