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.
CodePudding user response:
Var i
is globally-scoped, so by using var i=0
you are definitely creating scope conflict. Use let
or another variable name instead.
CodePudding user response:
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[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]);
CodePudding user response:
That's the problem with var
s. 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.