Reputation: 350
I don't understand what is the problem here, when i put
array.length
inside for loop it's giving wrong length.
let x = 'w3resource'
let y = x.split('');
let output = [];
// let len = y.length;
for(let i = 0; i < y.length; i++){
let z = y.pop();
output.push(z);
}
let alfa = output.join('');
console.log(alfa);
Now when i put it outside it's working correctly.
let x = 'w3resource'
let y = x.split('');
let output = [];
let len = y.length;
for(let i = 0; i < len; i++){
let z = y.pop();
output.push(z);
}
let alfa = output.join('');
console.log(alfa);
Please explain what's going on here?
Upvotes: 0
Views: 1064
Reputation: 157
Array.prototype.pop() is mutable method in JavaScript.
So, when you pop()
out elements from array, the array y
is updated.
For loop mechanism
i == 0 and y == 10, i< y.length
condition true, z = y.pop()
and y.length
becomes 9
i == 1 and y == 9, i< y.length
condition true, z = y.pop()
and y.length
becomes 8
i< y.length
condition true, z = y.pop()
and y.length
becomes 7< y.length
condition true, z = y.pop()
and y.length
becomes 6i< y.length
condition true, z = y.pop()
and y.length
becomes 5i< y.length
condition false, loop exits.Upvotes: 1
Reputation: 100
first run:
i = 0; y = ["w","3","r","e","s","o","u","r","c","e"]; y.length = 10;
y.pop() => y =["w","3","r","e","s","o","u","r","c"]; y.length =9;
second run:
i = 1; y.length = 9;
...
continue like that the length of y array get smaller so its why you got result = 'ecruo';
Upvotes: 1
Reputation: 769
Because everytime you call pop
method y.pop() , the length of an array changes (y.length).
There are some methods in javascript which mutate objects internally upon calling them, such as pop
and push
Upvotes: 3
Reputation: 97381
In the first case, y.length
is re-evaluated on every iteration. Since you're popping elements from the array, the array gets smaller on every iteration, and the value of y.length
decrements by 1.
This is why you only have 5 characters in the output of your first snippet.
Iteration | i | y.length
-----------|-----|----------
1 | 0 | 10
2 | 1 | 9
3 | 3 | 8
4 | 4 | 7
5 | 5 | 6
Upvotes: 6
Reputation: 3122
let x = 'w3resource'
let y = x.split('');
let output = [];
// let len = y.length;
for (let i = 0; i < y.length; i++) {
let z = y[i];
output.push(z);
}
let alfa = output.join('');
console.log(output);
y.pop() function method removes the last element from an array and returns that element, so whenever you called it the variable y will have less length than previous. so your code is perfect just need to correction at y.pop().
Upvotes: 0