1

I want to iterate the array, however, after printing out all values in the array, it prints an undefined, I wondered why this is happening and how I can fix it. Thanks!

var utilities = {
    printAllMembers:function(targetObject){
        for(i in targetObject){
            document.write("<br>"+targetObject[i]);
        }
    }
}
var batman=[];
    batman[0]="batman";
    batman[1]="batman@bat.man";
    batman[2]="male";

document.write(utilities.printAllMembers(batman));
pokemon king
  • 33
  • 1
  • 5

2 Answers2

3

it prints an undefined, I wondered why this is happening...

Because you've told it to here:

   document.write(utilities.printAllMembers(batman));
// ^

That will call utilities.printAllMembers, and then it will output the result of calling the function. Since the function doesn't return a value, the result of calling it is undefined.

...and how I can fix it

To just call it, just call it:

utilities.printAllMembers(batman);

Side note: Don't use for-in (without safeguards) to loop through array indexes, that's not what it's for. This answer has a full discussion and the various options you have for looping through arrays.


Side note 2: Your code is falling prey to The Horror of Implicit Globals because you never declare i. Remember to declare your variables, with var (through ES5) or let (ES6+, not yet well-supported in the wild as of August 2015).

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

The problem is using document.write() twice - in the printAllMembers() function and when you call that function. As mentioned above the for-in loop is malformed and misused - instead use a regular for-loop or a while-loop as below.

var utilities = {
    printAllMembers:function(targetObject){
        var i = 0;
        while(i < targetObject.length){
            document.write("<br>"+targetObject[i]);
            i += 1;
        }
    }
};
var batman=[];
    batman[0]="batman";
    batman[1]="batman@bat.man";
    batman[2]="male";

utilities.printAllMembers(batman);

See This Link for more info on Loops and Iteration.

Brian Peacock
  • 1,801
  • 16
  • 24