Reputation: 21
I'm trying to make a function that will store all integers from 0 up to and including x in an array.
function range(x){
for(var counter = 0; counter <= x; counter++)
show(counter);
}
var rangeArray = [range(4)];
show(rangeArray);
This will give me 0, 1, 2, 3, and 4 (but not in an array :(), then, as if taunting me, put undefined in an array all by its lonesome.
Where is this undefined coming from, and why don't the other values go in the array?
Upvotes: 1
Views: 558
Reputation: 1675
We have a basic function called range that is similar in functionality to Pythons range function. This is a simple and effective array generator.
// Function to return array from 0-x
function range(x) {
// Start with an empty array
var arr = [],
i = -1;
// Loop through values from 0-X
for(;i++ < x;) {
// Add number to array
arr.push(i)
}
// Return array
return arr;
}
var rangeArr = range(5) //returns [0, 1, 2, 3, 4, 5]
Upvotes: 0
Reputation: 16526
JavaScript functions always return undefined
when you have not explicitly called return
. Except in the case when you called the function
with new
. In that case the function returns this
(a reference to the object that was created).
function foo() {
}
foo() // returns undefined
new foo() // returns a reference to the object that was created
Convention dictates that if a function is to be used as a constructor that it is capitalized
function Foo() {
this.x = 5;
// return this; // is implicit
}
This convention is helpful because really bad stuff will happen if you call the function Foo
and forget to quantify it with new
.
x = 42
Foo() // this mistake is easier to spot if the function is capitalized
// x is now equal to 5.
x = 42
f = new Foo()
// x is still 42 and f.x is 5
Why do the values not go into the array?
A program can not simply print values into its own source code. To do so would be mind bogglingly impossible to reason about. The other answers on this page are both good solutions to your specific problem.
Upvotes: 0
Reputation: 4360
This is what you want:
function range(x){
var result = [];
for(var counter = 0; counter <= x; counter++) {
result.push(counter);
show(counter);
}
return result;
}
var rangeArray = range(4);
show(rangeArray);
Upvotes: 1