Reputation: 332
I've just started an exercise in Chapter 4 of a book called Eloquent JavaScript. The exercise asks me to do the following:
"Write a range function that takes two arguments, start and end, and returns an array containing all the numbers from start up to (and including) end."
However, when I write the following code:
function range(start, end) {
array = [];
for (var i = start; i <= end; i += 1) {
array.push(i);
}
return array;
}
console.log(range(5, 2));
It returns square brackets ( [] ). Does anyone know what the issue might be? Thanks a bunch!
Upvotes: 0
Views: 1144
Reputation: 510
Returning square brackets indicates an empty list. This may or may not be the desired result.
To expand on your question a bit - you could use a range function that is more flexible and able to produce descending lists. See below for example, or in this fiddle.
function range(start, end) {
array = [];
// Determine order
var delta = (start < end)? 1 : -1;
for (var i = start; num_compare(i,end,delta); i += delta) {
array.push(i);
}
return array;
}
function num_compare(a,b, delta) {
if(delta == 0) { return false; } // No change? Avoid infinite loop.
if(delta < 0) { return a >= b; } // Descending. Continue while a>=b
if(delta > 0) { return a <= b; } // Asecending. Continue while a<=b
}
var answer = range(5,2);
console.log(answer);
document.getElementById("answer").innerHTML = answer.toString();
Now passing in range(5,2);
will produce the (maybe desired) list of [5,4,3,2].
Related questions/answers of note include: reversing order in for loop, comparison operators
Upvotes: 0
Reputation: 4820
You are passing the range indexes in the wrong order. You cant go from 5 to 2, you need to go from 2 to 5
range(2,5)
Upvotes: 2