Reputation: 399
I need to print a range of numbers in a range using a function and a for-loop. Again I'm stuck on the return value. I believe my code is sufficient for the task but if you have a better idea I'm all ears.
function printRange(rangeStart, rangeStop) {
var text = "";
for (var i = rangeStart; i < rangeStop; i++) {
text += i + ',';
}
return text;
var result = text;
}
printRange(20, 47);
The 'result' is ought to print the numbers 20,21,22...,46,47 but of course it doesn't... Any help is appreciated. Regards, Thomas
Upvotes: 1
Views: 5976
Reputation: 19
function printAllNum(rangeStart, rangeEnd){
for(let i = rangeStart; i <= rangeEnd; i++) {
document.write(i + " ")}
}
printAllNum(1,20);
Upvotes: 0
Reputation: 30330
There are two things you need to fix - your code doesn't print rangeStop
, but it does include a trailing comma.
You can fix the former by changing your loop end condition to use <=
, and String.prototype.slice
can do the latter.
function printRange(rangeStart, rangeStop) {
var text = "";
for (var i = rangeStart; i <= rangeStop; i++) {
text += i + ',';
}
return text.slice(0, -1);
}
document.write(printRange(20, 47));
Upvotes: 2