I have a class that have 10 elements and when I push my array it is returning just one element. What is the issue with the script?
`function() { var vins = document.querySelectorAll('.dws-vehicle-listing-item-field.dws-vehicle-field-vin');
for (var i = 0; i < vins.length; i ) {
var array = [];
var items = vins[i].innerText.replace(/ /g, "").split('\n')[2];
array.push(items);
}
return array;
}`
I tried to add some exclusions based on code string, but even that it didn't work. Still returning just one element
CodePudding user response:
The issue here is that you are redeclaring a new array instance each time you loop. The solution is to initialise the array variable outside the loop;
let array = [];
for (let i = 0; i < vins.length; i ) {
let items = vins[i].innerText.replace(/ /g, "").split('\n')[2];
array.push(items);
}
return array;
Also, I recommend you not to use var
, but using const
(for values which do not change) or let
instead: more on this