如何用“ let”和“ const”替换此代码中的“ var”关键字?

时间:2019-04-09 16:41:48

标签: javascript ecmascript-6

如果将“ var”关键字替换为“ let”或“ const”,则会出现userChoice未定义错误。

我已经尝试用“ let”或“ const”替换所有内容。我还将userChoice放入函数中,并在需要时调用该函数。我还尝试将整个while循环放入函数中。该程序与“ var”完美配合。

使用“ let”和“ const”获得的最大距离是/一旦尝试将其放入while循环,它将停止工作:

const arrayList = [];
let userChoice = prompt('What would you like to do?');
// Array list is empty array
if (userChoice === "new") {
    let newTodo = prompt('Enter a new todo');
    arrayList.push(newTodo);
} else if (userChoice === "list") {
    console.log(arrayList);
}

工作代码:

var arrayList = [];
var userChoice = prompt('What would you like to do?');
// Array list is empty array
while (userChoice !== "quit") {
    if (userChoice === "new") {
        var newTodo = prompt('Enter a new todo');
        arrayList.push(newTodo);
    } else if (userChoice === "list") {
        console.log(arrayList);
    }
    var userChoice = prompt('What would you like to do?');
}

我希望该程序不断提示您,除非您说“退出”。您输入“ new”添加新的待办事项,然后输入“ list”列出所有待办事项。

1 个答案:

答案 0 :(得分:2)

问题在于该代码两次声明userChoice,而第二个var是不必要的:

var arrayList = [];
var userChoice = prompt('What would you like to do?');
// Array list is empty array
while (userChoice !== "quit") {
    if (userChoice === "new") {
        var newTodo = prompt('Enter a new todo');
        arrayList.push(newTodo);
    } else if (userChoice === "list") {
        console.log(arrayList);
    }
    var userChoice = prompt('What would you like to do?');
//  ^^^---------------------------------------------------- here
}

使用var并不重要,因为var具有函数作用域(或全局作用域,如果在函数外部使用),并且忽略了多个声明,但是对于let来说却很重要let块作用域,因此在块中声明新的userChoice会遮盖外部的let。 (使用var的多个声明在同一范围内是一个错误,因为这样做是没有意义的,并且允许这样做会有复杂的事情。)

只需删除第二个var并用let替换其他const(或者您可以将arrayList用于newTodoarrayList ,除非未显示代码,否则稍后会为const arrayList = []; // Or let let userChoice = prompt('What would you like to do?'); // Array list is empty array while (userChoice !== "quit") { if (userChoice === "new") { const newTodo = prompt('Enter a new todo'); // Or let if you prefer arrayList.push(newTodo); } else if (userChoice === "list") { console.log(arrayList); } userChoice = prompt('What would you like to do?'); } 分配一个新数组):

eq