I am trying to empty an array by using the pop method after that I want to push the returned result of the pop method to another array and get the full result, but the pop method doesn't satisfy my needs it always stops midway what is the problem?
let arr = [1,2,3,4,5,6,7]
let newArr = []
//console.log(arr.pop())
const fib = function(n){
if(n <= arr.length){
newArr.push(arr.pop())
return fib(n+1)
}
}
fib(0)
console.log(newArr)
let arr = [1,2,3,4,5,6,7]
let newArr = []
//console.log(arr.pop())
const fib = function(n){
if(!n <= 0){
newArr.push(arr.pop())
return fib(n-1)
}
}
fib(arr.length)
console.log(newArr)
I would do like that:
var myArr = [1,2,3,4,5,6,7,8,9];
var myNewArr = [];
while(myArr.length){
myNewArr.push(myArr.pop());
}
console.log(myArr, myNewArr);
If you just want to reverse it you could use the reverse function for Arrays:
var myArr = [1,2,3,4,5,6,7,8,9];
myArr = myArr.reverse();
console.log(myArr);
// Or if you really need 2 variables and one needs to be empty
var myArr = [1,2,3,4,5,6,7,8,9];
var myNewArr = myArr.reverse();
myArr = [];
console.log(myArr, myNewArr);
If you want your array empy... I think this is the easiest way.
var array = [1,2,3,4,5,6,7]
array = []
console.log(array)