繁体   English   中英

为什么这会导致无限循环?

[英]Why is this causing an infinite loop?

我对JavaScript相对较新,并且正在尝试制作一个简单的脚本。 基本上,我希望它在一个名为ROBLOX的网站上找到某商品的最低价格。 由于某种原因,此脚本导致了无限循环,从而使我的Chrome崩溃了。 谁能帮忙

function getLowest(id) {
    var give;
    for (var page = 1; page < 33; page++) {
        var link = "http://www.roblox.com/catalog/browse.aspx?CatalogContext=1&Subcategory=9&CurrencyType=0&pxMin=0&pxMax=0&SortType=0&SortAggregation=3&SortCurrency=0&PageNumber=" + page + "&IncludeNotForSale=false&LegendExpanded=true&Category=3";
        $.get(link, function(data) {
            for (var item in data) {
                if (data[item]["AssetId"] == id) {
                    give = data[item]["BestPrice"];
                }
            }
        })
    }
    if (give) {
        return give;
    }
}

console.log(getLowest(prompt("Enter the ID to find the lowest price of")));

我真的知道了,谢谢您的帮助。

我最终得到的是:

function getLowest(id) {
    for (var page = 1; page < 33; page++) {
        var link = "http://www.roblox.com/catalog/json?browse.aspx?CatalogContext=1&Subcategory=9&CurrencyType=0&pxMin=0&pxMax=0&SortType=0&SortAggregation=3&SortCurrency=0&PageNumber=" + page + "&IncludeNotForSale=false&LegendExpanded=true&Category=3";
        $.get(link, function(data) {
            for (var item in data) {
                if (data[item]["AssetId"] == id) {
                    console.log(data[item]["BestPrice"]);
                    return;
                }
            }
        })
    }
}

getLowest(prompt("Enter the ID to find the lowest price of"));

您没有面临无限循环问题,而是异步加载问题。

for (var page = 1; page < 33; page++) {
    $.get(link, function(data) {
        for (var item in data) {
            if (data[item]["AssetId"] == id) {
                give = data[item]["BestPrice"];
            }
        }
    })
}

假设您使用jQuery的$.get查询这些页面,则$.get的默认行为是异步查询页面。 因此,该循环将完成,而无需等待$.get所有回调,这表明退出循环时, give将保持未定义状态。

解决方案将是您在答案中建议的解决方案,或者

  • 通过使用$.ajax({ url: link, async: false }).done(function(data) {})强制$.get同步
  • 使用async.js进行异步收集,并在完成所有查询工作后使用回调重写该函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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