为什么这会导致一个无限循环

Why is this causing an infinite loop?

本文关键字:一个 无限循环 为什么      更新时间:2023-09-26

我对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进行async集合,并在完成所有查询工作后用回调重写函数