Javascript无限循环发生没有明显的原因

时间:2015-03-24 20:33:05

标签: javascript html loops

当屏幕冻结时,我正在为我的网站开发搜索引擎。我假设有一个无限循环,但我没有发现任何验证服务的错误。我可以得到一些帮助吗?

<input id="Query" value="Type search here"></input>
<input id="button" type="submit" name="button" value="Search"/>
<script>
var titles = ["Pacman", "Tu95", "Tank Trouble", "HTML", "Test", "Print", "Search"];
var links = ["http://www.mikeyrichards.co.vu/2015/03/pacman.html", "http://www.mikeyrichards.co.vu/p/tu95_23.html", "http://www.mikeyrichards.co.vu/p/tu95.html", "http://www.mikeyrichards.co.vu/2015/03/html-i-used-html-for-this-console.html", "http://www.mikeyrichards.co.vu/2015/03/test-post.html", "http://www.mikeyrichards.co.vu/2015/03/print-page.html", "http://www.mikeyrichards.co.vu/2015/03/search.html"];
var titleswork = [];
var titlesworknumbers = [];
document.getElementById('button').onclick = function() {
    titleswork = [];
    titlesworknumbers = [];
    if (document.getElementById("results")) {
        var clear = document.getElementById("results");
        clear.parentNode.removeChild(clear);
    }
    var letterthroughdata = 0;
    var data = document.getElementById("Query").value;
    for (var i = 0; i < titles.length; i++) {
        if (titles[i].length < data.length) {} else {
            while (letterthroughdata < data.length) {
                if (titles[i] === data[letterthroughdata]) {
                    letterthroughdata++;
                }
            }
            if (letterthroughdata === data.length) {
                titleswork.push(titles[i]);
                titlesworknumbers.push(i);
            }
        }
    }
};
console.log(titleswork);
console.log(titlesworknumbers);
var x = document.createElement("div");
x.setAttribute("id", "results");
for (var i = 0; i < titleswork.length; i++) {
    var y = document.createTextNode(titleswork[i] + ": " + links[titlesworknumbers[i]]);
    x.appendChild(y);
    var brake = document.createElement("br");
    x.appendChild(brake);
    var z = document.getElementById("post-body-2820145598585075365");
}
z.appendChild(x);
</script>

1 个答案:

答案 0 :(得分:1)

这是一个无限循环:

while (letterthroughdata < data.length) {
    if (titles[i] === data[letterthroughdata]) {
        letterthroughdata++;
    }
}

如果您遇到letterthroughdata小于data.lengthtitles[i]不等于data[letterthroughdata]的情况,则会永远循环。