var arr = [1,2,3,4,5]
for (var i = 2; i < arr.length; i ) {
[arr[i], arr[i 1]] = [arr[i 1], arr[i]]
}
console.log(arr);
I have no idea why this is an infinite loop..
CodePudding user response:
Executing this will give you a sense of what happens.
async function inifiniteLoop() {
var arr = [1, 2, 3, 4, 5];
for (var i = 2; i < arr.length; i ) {
[arr[i], arr[i 1]] = [arr[i 1], arr[i]];
console.log(arr);
console.log(`i: ${i}; arr.length: ${arr.length}`);
await sleep(2000);
}
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
(async () => await inifiniteLoop())();
While you would get an IndexOutOfBounds
exception in Java and many other languages this works in JavaScript.
const array = [34]
console.log(array)
array[3] = 23
console.log(array)