简体   繁体   中英

Javascript for loop until - multiple conditions

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!

You should use && instead of || . Also, $i should be i .

for(var i=0, img; (img = imgs[i]) && (i < 12); i++)
     found.push(img);

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];
}

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]);
}

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]){

....

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM