我正在使用 code.org,并且尝试从数组返回该项目,但在第 34 行收到错误,指出 possibleFoods[selectedFood] 未定义。我不明白为什么,这就是阻止食物选择 block 发挥作用的原因吗?我应该如何正确定义 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
未定义。不确定如何定义。
最佳答案
未声明 selectedFood 变量。此外,您将其分配在嵌套的 if 条件内,而这可能并不总是正确。
试试这个:
在 if 语句之前在外部声明 selectedFood 并指定初始值。
var selectedFood = 0;
关于javascript - 从数组中返回正确的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57801528/