gpt4 book ai didi

javascript - 循环中的 Switch 语句记录错误值

转载 作者:行者123 更新时间:2023-12-03 11:27:34 24 4
gpt4 key购买 nike

我有一个如下所示的 switch 语句:

subCatTDs = 8;

switch(subCatTDs){
case 3:
//Do some code
case 2:
//Do some code
case 8:
console.log(subCatTDs);
}

我从代码的其余部分简化了这一点,以尝试解决正在发生的问题。 subCatTDs 确实设置为不同的值(并且是更大循环的一部分),但您可能会认为在这种情况下,我在 switch 语句之前明确声明了它的值,并且控制台正在打印(正如我所说,它处于循环中):

3
8

当我直接在语句之前设置值时,为什么它会显示“3”?

编辑

这里是更多代码。对于更宏伟的计划来说,它可能没有太大意义,但它可能会有所帮助(这是一个非常复杂的插件,因此很难在这里包含所有内容;如果您需要澄清任何内容,请告诉我):

for(i = 0; i < numberTRs; i++){
var subCatValue = i + 1;
var subCatRow = $('.subCatTable > tbody > tr:nth-child(' + subCatValue + ')');
var subCatTDs = subCatRow.find('> td').length;

//This used to be 5 now it's 4?
switch(subCatTDs){
case 3:
//Subcat Title
for(j = 0; j < subCatTDs; j++){
switch(j){
case 0:
case 2:
var nthChild = j + 1;
var subCatElement = $('.subCatTable tr:nth-child(' + subCatValue + ') td:nth-child(' + nthChild + ')');
var subCatTitle = subCatElement.html();
$('div#subcat-' + rowCounter + '-' + subCatCounter).append('<div class="subCatTitle">' + subCatTitle + '</div>');
subCatCounter++;
if(subCatCounter>subCatPerRow){
subCatCounter = 1;
}
}
}
case 2:
//First time through

//Second time through
if(case2==true){
rowCounter++;
case2 = false;
continue;
}

case2 = true;

case 8:
console.log(subCatValue);
for(j = 0; j < subCatTDs; j++){
switch(j){
case 0:
case 5:
//Get the appropriate nth-child
var nthChild = j + 1;
var subCatElement = $('.subCatTable tr:nth-child(' + subCatValue + ') td:nth-child(' + nthChild + ')');
var subCatImage = subCatElement.html();
$('div#subcat-' + rowCounter + '-' + subCatCounter).append('<div class="subCatImage">' + subCatTitle + '</div>');
subCatCounter++;
if(subCatCounter>subCatPerRow){
subCatCounter = 1;
}

case 3:
case 8:
var subCatDescrip = subCatElement.html();
$('div#subcat-' + rowCounter + '-' + subCatCounter).append('<div class="subCatImage">' + subCatDescrip + '</div>');
subCatCounter++;
if(subCatCounter>subCatPerRow){
subCatCounter = 1;
}
}
}
}
}

编辑器上的格式根本无法正常工作。一切都不一致,但我想我已经接近了。不确定这是否有意义,但您会看到我每次在 for 循环上循环时都会重置 subCatTD。它永远不应该打印出“3”,因为我仅在检查 8 的大小写后才使用 console.log(),但由于某种原因它确实如此。

任何帮助都会很棒。谢谢!

最佳答案

您需要在每个案例的末尾有一个break语句,否则处理将“失败”到下一个案例一直到最后。情况 8 中的打印将始终执行。

关于javascript - 循环中的 Switch 语句记录错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26857399/

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