为什么我的javascript无限运行?

时间:2014-09-22 21:44:23

标签: javascript

我正在控制台的Google日历中编写脚本,将学校日历中的所有活动添加到我自己的日历中。我基本上抓住了一个页面上的所有事件,点击它们,然后在事件页面上,我想点击添加到日历,然后返回,并在页面上完成全部点击。

然而,我的代码块似乎无限次地运行

var friendCheckList = document.getElementsByClassName("evt-lk"); 
console.log(friendCheckList.length)

for (var i = 0; i < friendCheckList.length; i++) 
{
    friendCheckList[i].click();
    var possibleReturn = document.getElementsByClassName("goog-imageless-button"); 
    var backArray = [];
    for (var i = 0; i < possibleReturn.length; i++)
    {
        console.log("Came here with some reason");
        console.log(possibleReturn.length);
        console.log(friendCheckList.length);
        var node = possibleReturn[i];
        if (node.getAttribute("title")=="Back to Calendar") node.click();
    }
};

知道为什么会无限次地运行?它反复记录“有些原因来到这里”10 13。 10是页面上的通风口数量,13是“goog-pixelless-buttons”的数量。

3 个答案:

答案 0 :(得分:1)

问题描述

  1. 执行嵌套fori值等于possibleReturn.length
  2. 看起来它小于friendCheckList.length - 1,因此您再次执行父for
  3. 在下一次执行中,嵌套i0设置为for,最后一次又以possibleReturn.length的值结束。
  4. 在嵌套i循环中重置for变量导致永远不会离开父循环。

    解决方案

    以秒为单位更改i变量名称(嵌套)for

    实施例

    更改

    for (var i = 0; i < possibleReturn.length; i++)
    

    为:

    for (var j = 0; j < possibleReturn.length; j++)
    

答案 1 :(得分:1)

因为您正在为第二个循环重复使用i变量。改为使用另一个标识符:

var friendCheckList = document.getElementsByClassName("evt-lk"); 
console.log(friendCheckList.length)

for (var i = 0; i < friendCheckList.length; i++) 
{
    friendCheckList[i].click();
    var possibleReturn = document.getElementsByClassName("goog-imageless-button"); 
    var backArray = [];
    for (var j = 0; j < possibleReturn.length; j++)
    {
        console.log("Came here with some reason");
        console.log(possibleReturn.length);
        console.log(friendCheckList.length);
        var node = possibleReturn[j];
        if (node.getAttribute("title")=="Back to Calendar") node.click();
    }
};

答案 2 :(得分:0)

您在外部循环和内部循环中使用相同的变量进行循环。每次启动内循环时,都会重置i的值。因此,只要possibleReturn.length&lt; freindCheckList.length循环将继续。

请改为尝试:

for (var i = 0; i < friendCheckList.length; i++) 
{
    friendCheckList[i].click();
    var possibleReturn = document.getElementsByClassName("goog-imageless-button"); 
    var backArray = [];
    for (var j = 0; j < possibleReturn.length; j++)
    {
        console.log("Came here with some reason");
        console.log(possibleReturn.length);
        console.log(friendCheckList.length);
        var node = possibleReturn[j];
        if (node.getAttribute("title")=="Back to Calendar") node.click();
    }
};