Reputation: 29
Why isn't this working? ps. I don't want to use any other variable to make it work, and i don't want to use built in functions, just asking why THIS is not working?
function reverse(arr){
for(var i =0; i< arr.length; i++){
arr.push(arr[arr.length-i]);
}
return arr;
}
Upvotes: 0
Views: 89
Reputation: 167172
There are a lot of flaws in your code.
arr.push(arr[arr.length-i]);
the array length increases, thereby, you won't get a consistency in the data.arr
is ahead of its length.It is better to use another variable and reverse, or you can use the built-in reverse()
function. There's nothing wrong in having another variable and add temporary contents in it.
Solutions:
Using a temporary array:
function reverse(arr) {
var final = [];
for (var i = arr.length - 1; i >= 0; i--) {
final.push(arr[i]);
}
return final;
}
function reverse(arr) {
return arr.reverse();
}
Using few temporary variables:
a = [5,4,3,2,1];
function reverse(arr) {
var i = 0, j = arr.length - 1;
for (i = 0; i < j; i++, j--) {
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return arr;
}
console.log(reverse(a));
Upvotes: 1
Reputation: 8926
I don't want to use any other variable to make it work, and i don't want to use built in functions
You cannot.
Use temporary array for result
function reverse(arr) {
var res = []
for (var i = arr.length - 1; i > -1; i--) {
res.push(arr[i]);
}
return res;
}
Upvotes: 0
Reputation: 594
You're going to run out of memory. What you're doing is adding what was initially the last element of that array infinitely to the end of your array. Every time that you call arr.push(...)
you increase arr.length
by one. Your for loop will never be able to finish because i
will never be less than arr.length
Upvotes: 0