gpt4 book ai didi

javascript - 循环闭合 - 我把它放在哪里?

转载 作者:行者123 更新时间:2023-11-28 00:13:10 26 4
gpt4 key购买 nike

关于previous post ,我很难弄清楚在哪里放置我用来匹配 JSON 返回的数组的循环闭包。

下面是我修改后的代码:

$(function()
{
var $reports = $('#repOut');
var techCount = 0;
var repCount = 0;
techs = ["Name_1", "Name_2"];

function counts(tech, count)
{
this.tech = tech;
this.count = count;
}
$.ajax(
{
type: 'GET',
url: 'https://api.trello.com/1/board/BOARD_ID/checklists?checkItem_fields=name,state&key=MY_KEY&token=MY_TOKEN',
dataType: 'jsonp',
success: function(data)
{
$.each(data, function(i, repName)
{
var items = repName.checkItems;
for (i = 0; i < items.length; i++)
{
for (var n = 0; n < techs.length; n++)
{
techName = techs[n];
}
var rex = new RegExp(techName, "i");
var num = /\(\d+\)/;
if (rex.test(items[i].name))
{
var repFull = items[i].name;
repName = repFull.replace(/\.*$|-.*$/, "");
if (num.test(items[i].name))
{
var repNum = parseInt(/\d+/.exec(items[i].name), 10);
repCount += repNum;
}
}
}
});
var techCount = new counts(techName, repCount);
$reports.after("<table border =1 id='reports'><tr><th>Tech</th><th>Count</th></tr><tr><td>" + techCount.tech + "</td><td>" + techCount.count + "</td></td></tr></table>");
}
});
});

该循环仅返回 Name_2JSON 值(但这一次,它已正确添加并显示在我的网页上)。我需要在我的 techs 数组中获取 EACH 名称的这些值并输出它们。我读过很多关于闭包的网站/文章/答案,但我就是不知道在哪里/如何将它放入我的代码中!

任何人都可以帮忙提供一个示例,说明我的代码在使用闭包时会是什么样子吗?我怀疑需要关闭是否正确?

最佳答案

感谢您的所有反馈!我想我只是需要有人“监视我”来帮助我看到明显的问题。下面是带有我的评论的固定代码。

$(function()
{
var $reports = $('#repOut');
var techCount = 0;
var techs = ["Name_1", "Name_2"];

function counts(tech, count)
{
this.tech = tech;
this.count = count;
}
$.ajax(
{
type: 'GET',
url: 'https://api.trello.com/1/board/BOARD_ID/checklists?checkItem_fields=name,state&key=KEY&token=TOKEN',
dataType: 'jsonp',
success: function(data)
{
for (var n = 0; n < techs.length; n++) //MOVED THE 'tech' LOOP UP HERE
{
var techName = techs[n]; //INCLUDING THE 'techName' VARIABLE DEFINITION
var repCount = 0;
$.each(data, function(_, repName)
{
var items = repName.checkItems;
for (var i = 0; i < items.length; i++)
{
var rex = new RegExp(techName, "i");
var num = /\(\d+\)/;
if (rex.test(items[i].name))
{
var repFull = items[i].name;
var repFullName = repFull.replace(/\.*$|-.*$/, "");
if (num.test(items[i].name))
{
var repNum = parseInt(/\d+/.exec(items[i].name), 10);
repCount += repNum;
}
}
}
})
//MOVED MY OBJECT DECLARATION UP IN THE LOOP
var techCount = new counts(techName, repCount);
$reports.after("<table border =1 id='reports'><tr><th>Tech</th><th>Count</th><tr><td>" + techCount.tech + "</td><td>" + techCount.count + "</td><br></td></tr></table>");
}
}
});
});

关于javascript - 循环闭合 - 我把它放在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30699648/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com