0

我正在使用 code.org,我试图从数组中返回项目,但在第 34 行收到一个错误,即可能的食物 [selectedFood] 未定义。我不明白为什么,这就是阻止食物选择块工作的原因吗?我应该如何正确定义 selectedFood?

setScreen("BaseScreen");
onEvent("selectionbutton", "click", function( ) {
    setScreen("food_decision_screen");
});
var selections = [true, true, true];
var possibleFoods = [
    {name:"Raw pasta prima vera", info:{recipe:"", prepTime:{total:20,cook:0,  prep:20}, image:""}},
    {name:"Zucchini chips",       info:{recipe:"", prepTime:{total:55,cook:30, prep:25}, image:""}}
];

var possibleFoods;
onEvent("preference_finished_button", "click", function( ) {
    selections = [
        getChecked("radio_buttonhot"),
        getChecked("radio_buttonvege"),
        getChecked("radio_button0-30") 
    ];

    if (selections[0] == false) {    
        if (selections[1] == false) {      
            if (selections[2] == true) {        
                selectedFood = 1;        
            }         
        }    
    }

    setText("t_textOutputFoodInfo", "total time: " + 
    possibleFoods[selectedFood].info.prepTime.total);
    setText("t_textOutput_foodSelectedName", "name: " + 
    possibleFoods[selectedFood].name);   
});

selectedFood未定义。不确定如何定义。

4

3 回答 3

2

未声明 selectedFood 变量。此外,您在嵌套的 if 条件中分配它,这可能并不总是正确的。

尝试这个:

在 if 语句之前用初始值声明 selectedFood 外部。

var selectedFood = 0;
于 2019-09-05T08:45:52.797 回答
0

你在这里有几个问题:

  1. selectedFood 没有被声明——例如它之前没有“const”、“var”或“let”。

  2. 如果您不了解作用域以及 var、const 和 let- 之间的区别,请阅读此处。然后你就会明白为什么最好selectedFood在块之前定义if,并且只填充里面的值,像这样:

    let selectedFood;    
    if (selections[0] == false) {    
       if (selections[1] == false) {  
          if (selections[2] == true) {   
             selectedFood = 1;    
          }    
       }
    }
    
于 2019-09-05T08:46:44.127 回答
0

selectedFood未定义只是因为它没有被声明,此外,在你的情况下永远不会到达这一行:selectedFood = 1;. 根据您要实现的目标,使用逻辑运算符构建您的条件。

替换这个:

if (selections[0] == false) {

if (selections[1] == false) {


if (selections[2] == true) {

selectedFood = 1;

} 

}

}

有了这个:

let selectedFood = 0; // Set by default to 0
if (!selections[0] && !selections[1] && selections[2]) {
selectedFood = 1;
}

希望这可以帮助!

编辑:如果您可以将我与您要解决的挑战联系起来,我可能会给出更直接的答案。

于 2019-09-05T08:49:34.257 回答