1

Hey so I am using puppeteer and when I run this code:

console.log(dealsId[i]);

for (var i = 0; i < sizes.length; i++) {
    var refIdClasses = await sizes[i].$eval('input', a => a.getAttribute('class'));
    if (refIdClasses != 'disabled') {
        var refId = await sizes[i].$eval('input', a => a.getAttribute('value'));
        var size = await sizes[i].$eval('input', a => a.getAttribute('data-size'));
        refIds.push({ size: size, refId: refId });
    }
}
console.log(dealsId[i]);

The Deals Id works before the for loop and after the loop it says undefined and I am so confused on why.

0

3 Answers 3

3

Var i is globally-scoped, so by using var i=0 you are definitely creating scope conflict. Use let or another variable name instead.

Sign up to request clarification or add additional context in comments.

Comments

1

That's the problem with vars. You can declare and re-declare them in the same scope without warning.

I assume you declared a var i in the code before what you showed, but you re-declare it in the for loop. i < sizes.length being the condition to break the loop, the loop break and i is now out-of-bounds of your array, hence the undefined (if dealsId has a size that's inferior to sizes array).

It isn't "unrelated" since you used the same variable to loop through 2 different arrays. Since we don't know if the two arrays have the exact same size, we can't pinpoint with 100% accuracy what's going on, but I'll go with that.

Comments

0

This is because your for loop is also using i to iterate, possibly conflicting with the i in dealsId[i].

Possible solution might be to change the variable in for loop from i to j.

The code becomes:

console.log(dealsId[i]);

for (var j = 0; j < sizes.length; j++) {
    var refIdClasses = await sizes[j].$eval('input', a => a.getAttribute('class'));
    if (refIdClasses != 'disabled') {
        var refId = await sizes[j].$eval('input', a => a.getAttribute('value'));
        var size = await sizes[j].$eval('input', a => a.getAttribute('data-size'));
        refIds.push({ size: size, refId: refId });
    }
}
console.log(dealsId[i]);

3 Comments

Yes, it's a possible solution, but a good solution is to use a for...of loop, that doesn't need a useless index variable at all.
Probably sizes[i] needs to be sizes[j].
@CasimiretHippolyte you can revert the downvote :) i have edited the code for it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.