1

我有一个显示多咖啡值的 js 代码...如果我试图显示单值咖啡...它不会进入 else if...我修改了现有代码但出现未定义的错误...你能告诉我如何解决它

var multCoffees = false;
var singleCoffee = false;
if (Coffees.length > 1) {
    multCoffees = true;
}
if (Coffees.length > 1) {
    singleCoffee = true;
}
if (apptTimeCell) {
    apptTimeHTML = MyDay.dish(allData, multCoffees, singleCoffee);
    apptTimeCell.innerHTML = apptTimeHTML;
} else {
    apptTimeCell = Util.cep("span", {
        className: "appt-time"
    });
    patientRowTD.insertBefore(apptTimeCell, patCell);
}
dish: function (allData, multCoffees, singleCoffee) {
    if (multCoffees) {
        var htmlArr = [];
        htmlArr.push(allData.APPT_TIME_DISPLAY, "<br/><span class='sub-detail'>", allData.MNEMONIC, "</span>");
        console.log("multiCoffee" + allData.PROVIDER_MNEMONIC);
        return htmlArr.join("");
    } else if (singleCoffee) {
        console.log("inside if" + allData.PROVIDER_MNEMONIC);
        var htmlArr = [];
        htmlArr.push(allData.APPT_TIME_DISPLAY, "<br/><span class='sub-detail'>", allData.PROVIDER_MNEMONIC, "</span>");
        console.log("singleCoffee" + allData.PROVIDER_MNEMONIC);
        return htmlArr.join("");
    } else {
        return allData.APPT_TIME_DISPLAY;
    }
},

工作代码

var multCoffees = false;
if (Coffees.length > 1) {
    multCoffees = true;
}
if (apptTimeCell) {
    apptTimeHTML = MyDay.dish(allData, multCoffees);
    apptTimeCell.innerHTML = apptTimeHTML;
} else {
    apptTimeCell = Util.cep("span", {
        className: "appt-time"
    });
    patientRowTD.insertBefore(apptTimeCell, patCell);
}
dish: function (allData, multCoffees) {
    if (multCoffees) {
        var htmlArr = [];
        htmlArr.push(allData.APPT_TIME_DISPLAY, "<br/><span class='sub-detail'>", allData.MNEMONIC, "</span>");
        console.log("multiCoffee" + allData.PROVIDER_MNEMONIC);
        return htmlArr.join("");
    } else {
        return allData.APPT_TIME_DISPLAY;
    }
},
4

2 回答 2

4

假设 Coffees.length 是 2。你这样做......

if (Coffees.length > 1) {
    multCoffees = true;
}

...和 ​​2 > 1,所以现在 multCoffees 是真的,但是你这样做,它检查同样的事情......

if (Coffees.length > 1) {
    singleCoffee = true;
}

而且,由于 2 > 1 仍然存在,现在 multCoffee 和 singleCoffee 都是正确的。所以当你尝试做

if (multCoffees) {
   ...
} else if (singleCoffee) {
   ...
}

第一个 if 分支为真,因此它被执行,而 else 分支因此被忽略(尽管它也为真)。您可能打算改为从

if (Coffees.length == 1) {
    singleCoffee = true;
} else if (Coffees.length > 1) {
    multCoffees = true;
}
于 2013-08-09T16:12:30.990 回答
3

用这个块替换你的前两个 if:

if (Coffees.length == 1) {
    singleCoffee = true; 
}
else if(Coffees.length > 1){
   multCoffees = true;
}

然后再试一次!

于 2013-08-09T16:19:04.960 回答