if else变量scope在js中的else中显示undefined

时间:2013-08-14 16:49:28

标签: javascript jquery html

我在htmlARR块中定义了一个名为if/else的变量。如果我在else块中注释掉该变量,则会显示 undefined ,但如果我没有对其进行评论,则会显示结果。

注意:我的变量范围也不在其他地方。

coffeeAllColGenHTML : function (allData, more) {
            console.log("WATER" + allData.WATER);
            console.log("providerWATER" + allData.PROVIDER_WATER);

            if (more) {
                var htmlArr = [];
                htmlArr.push(allData.COFFEE_DISH, "<br/><span class='sub-detail'>", allData.WATER, "</span>");
                return htmlArr.join("");
            } else {
/* this line */ //var htmlArr = [];
                htmlArr.push(allData.COFFEE_DISH, "<br/><span class='sub-detail'>", allData.PROVIDER_WATER, "</span>");
                return htmlArr.join("");
                //return allData.COFFEE_DISH;
                //console.log(allData.COFFEE_DISH);
            }
        },

1 个答案:

答案 0 :(得分:10)

您需要确定变量声明的范围:

coffeeAllColGenHTM: function (allData, more) {
        console.log("WATER" + allData.WATER);
        console.log("providerWATER" + allData.PROVIDER_WATER);
        var htmlArr = [];

        if (more) {
            htmlArr.push(allData.COFFEE_DISH, "<br/><span class='sub-detail'>", allData.WATER, "</span>");
            return htmlArr.join("");
        } else {
            htmlArr.push(allData.COFFEE_DISH, "<br/><span class='sub-detail'>", allData.PROVIDER_WATER, "</span>");
            return htmlArr.join("");
            //return allData.COFFEE_DISH;
            //console.log(allData.COFFEE_DISH);
        }
    },