Reputation: 381
function reverse(num) {
let newwarray = [];
let temparray = [];
var x = num.toString();
for (var i = x.length - 1; i >= 0; i--); {
newwarray += x[i]
}
return newwarray;
}
document.write(reverse(3456))
So the title basically says it all. The result is undefined and I can't find the problem by using Console.
Upvotes: 0
Views: 72
Reputation: 47
Try this, it reverses the number by making a new array
var number = 12345;
var stringArray = number.toString().split("");
var generatedReverse = [];
/* Loop through array of numbers */
for(i = 0; i < stringArray.length; i++){
var rev = stringArray[stringArray.length - 1 - i];
generatedReverse.push(rev);
}
var reverseFinal = generatedReverse.join("");
document.write(reverseFinal);
Upvotes: 1
Reputation: 138437
There are two little mistakes you've made.
The first one is the semicolon at the end of the line here:
for (var i = x.length - 1; i >= 0; i--);
Due to that, the stuff in the brackets in the following lines, is not the loops body. It's a seperate statement. The loops body is that single semicolon ;
.
Therefore what happens is that the loop runs, till the end condition is met (when i
is -1), then the block behind it runs, and does:
{
newwarray+=x[i]
}
And the -1
position of x
is undefined
. Now if you add an array and undefined
, both the array and undefined will be casted to a string (an empty array is turned into an empty string), and you end up with "undefined"
.
To make it working, remove the semicolon, and .push
to the array:
for (var i = x.length - 1; i >= 0; i--) {
newwarray.push(x[i]);
}
As a sidenote, the first mistake was only possible because you used var
, which declares i
not only in the loop's body, but in the whole function. I strongly recommend using let
to spot such errors more easily:
for(let i = 1; i < 0; );
{
console.log(i); // ReferenceError: i is not defined
}
Upvotes: 2
Reputation: 2587
If you have to reverse the number then you can make use of Array.prototype.reverse
function by doing a trick
function reverse(num){
let arr = num.toString().split("");
arr = arr.reverse();
return arr.join("")
}
document.write(reverse(3456)); //6543
Upvotes: 2