Reputation: 29
I'm currently trying to print out the values of an array in JavaScript and I keep receiving 'undefined' output in the Chrome developer console where I'm running the following code:
function printArray(){
var arr = [];
for (var i = 0; i < arr.length; i++){
arr = arr[i];
}
}
printArray(['hello','world',1,2,3]);
Will someone please point out to me what I am doing wrong here that is preventing me from seeing the following returned in the console?
['hello','world',1,2,3]
Additionally I've tried wrapping my call to the printArray
function inside of a console.log();
statement.
console.log(printArray(['hello','world',1,2,3]));
Upvotes: 0
Views: 56
Reputation: 11725
Any reason why you wouldn't just console log the whole array?
console.log(['hello','world',1,2,3]);
Upvotes: 0
Reputation: 1015
First, you have to pass the array as argument to the function. Second, inside the function you can use the console.log
to print each item of the array.
function printArray(arr){
for (var i = 0; i < arr.length; i++){
console.log(arr[i]);
}
}
printArray(['hello','world',1,2,3]);
You can also use console.log(['hello','world',1,2,3])
without the need of the printArray
function
Upvotes: 3
Reputation: 3967
This will print all the values in the array:
function printArray(arr){
for (var i = 0; i < arr.length; i++){
console.log(arr[i]);
}
}
printArray(['hello','world',1,2,3]);
Upvotes: 1