Javascript for循环直到 - 多个条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12691142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:02:03  来源:igfitidea点击:

Javascript for loop until - multiple conditions

javascriptfor-loop

提问by Darren Sweeney

I am using javascript, using regex to scrape images from html code.

我正在使用 javascript,使用正则表达式从 html 代码中抓取图像。

I want the loop to run either until the script finds no more images or until it reaches 12.

我希望循环运行直到脚本找不到更多图像或直到它达到 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!

对 javascript 很陌生,但正在尝试!

回答by I Hate Lazy

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

你应该使用&&而不是||. 另外,$i应该是i

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

回答by Alnitak

Assuming that you want foundto contain those first 12:

假设您要found包含前 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 imgsis only a pseudo-array, and not a real array.

你必须使用[].slice.call(imgs, ...)而不是imgs.slice()因为imgs它只是一个伪数组,而不是一个真正的数组。

An alternative to writing [].sliceis Array.prototype.slice.

写作的另一种选择[].sliceArray.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:

如果你想在循环中做其他事情,只需使用上面创建的数组来确保你只处理前 12 张图像:

for (var i = 0, n = found.length; i < n; ++i) {
    // do something with found[i];
}

回答by epascarello

I personally hate when people do assignment in the condition clause of a forloop, since it looks like someone mistook an assignment (=) for a comparison (===or ==). Better to do the logic elsewhere.

我个人讨厌人们在for循环的条件子句中进行赋值,因为看起来有人将赋值 ( =)误认为是比较 ( ===or ==)。最好在别处做逻辑。

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