Can someone please tell me what’s wrong here? console is showing exactly the same arr input and I just don’t understand why. There’s is nothing wrong with the forEach statement, I just checked it. It looks like the while is not running . It should be evaluating flat..
Your code so far
function steamrollArray(arr) {
let flat=[...arr];
while(flat.some(function(x) {return typeof x=="object";})) {
let arr=[...flat];
let flat=[];
arr.forEach(function(x) {
if(typeof x=="object") {
flat.push(...x);
} else {
flat.push(x);
}
});
}
console.log(flat);
return flat;
}
steamrollArray([1, [2], [3, [[4]]]]);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36 Edg/118.0.2088.69
Okay, that worked. But do you know why that happens? since it didn’t show me any error messages I supposed it was okey to declare it again inside the while loop. I just forgot there was no need to put the let in front of it once you did it before.
Copy the failing test case. Paste it into your code editor. See what happens.
The error message you get is separate from the shadowing problem. Shadowing is valid syntax. Ist just usually not doing what you intend. It’s legal to redeclare a variable inside of a smaller scope.
…
You cropped right before the error message…
This error message happens because of the shadowing! (The outer flat never changes, so you can never change the result of the loop exit test)
If you fix the shadowing, then you get another error message!
Your browser can’t tell you why you made an infinite loop in this case so you have to dig into what could be causing the loop never to stop. Then you have to dig into what’s being spread when it should not be.
I sent you pictures as well where it appears. Whenever I got that message I check that my while is not missing an increment or having a wrong condition. I checked both, so really hard to say the problem had to do with the re-declaring just from that error…
Alright, This right here i didn’t know! So the variable inside the loop is actually a local variable. That’s why it let me to declare it twice. So the loop will use the local variable instead of the outer one(and will keep it as local). So loops can have their own local scope.
About the other error i iknow that arrays and objects are both type objects, so I was expecting that. I already checked that Array.isArray() function out.
Hey, Thank you again for taking the time to solve my queries!