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);
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);
Share Improve this question asked Sep 23, 2019 at 3:33 AnkitAnkit 3504 silver badges17 bronze badges 0Please explain what's going on here?
5 Answers
Reset to default 6In 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
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
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';
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()
andy.length
bees 9i == 1 and y == 9,
i< y.length
condition true,z = y.pop()
andy.length
bees 8- i == 2 and y == 8,
i< y.length
condition true,z = y.pop()
andy.length
bees 7 - i == 3 and y == 7,
< y.length
condition true,z = y.pop()
andy.length
bees 6 - i == 4 and y == 6,
i< y.length
condition true,z = y.pop()
andy.length
bees 5 - i == 5 and y == 5,
i< y.length
condition false, loop exits.
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().
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745631746a4637151.html
评论列表(0条)