Reputation: 23979
I am using javascript, using regex to scrape images from html code.
I want the loop to run either until the script finds no more images or until it reaches 12.
I'm trying the following but not working:
var imgs = d.getElementsByTagName('img'), found = [];
for(var i=0,img; ((img = imgs[i]) || ( $i < 13)); i++)
Is this possible? Am I on the right lines?
Quite new to javascript but trying!
Upvotes: 18
Views: 50005
Reputation: 945
For Loop with multiple statements
let products= [...]
let users= [...]
for(let i=0,userParam = null, productParam=null; i<products.length; i++, userParam=products[i], productParam=products[i]){
....
}
Upvotes: 0
Reputation: 207501
I personally hate when people do assignment in the condition clause of a for
loop, since it looks like someone mistook an assignment (=
) for a comparison (===
or ==
). Better to do the logic elsewhere.
var imgs = d.getElementsByTagName('img'),
found = [],
i,
imgsLength = imgs.length,
max = imgsLength > 13 ? 13 : imgsLength;
for (i = 0; i < max; i++) {
found.push(imgs[i]);
}
or
var imgs = d.getElementsByTagName('img'),
found = [],
i,
imgsLength = imgs.length;
for (i = 0; i < 13 && i < imgsLength; i++) {
found.push(imgs[i]);
}
Upvotes: 3
Reputation: 48761
You should use &&
instead of ||
. Also, $i
should be i
.
for(var i=0, img; (img = imgs[i]) && (i < 12); i++)
found.push(img);
Upvotes: 23
Reputation: 339816
Assuming that you want found
to contain those first 12:
var imgs = d.getElementsByTagName('img');
var found = [].slice.call(imgs, 0, 12);
You have to use [].slice.call(imgs, ...)
instead of imgs.slice()
because imgs
is only a pseudo-array, and not a real array.
An alternative to writing [].slice
is Array.prototype.slice
.
If you want to do something else inside the loop, just use the array created above to ensure that you only work on the first 12 images:
for (var i = 0, n = found.length; i < n; ++i) {
// do something with found[i];
}
Upvotes: 5