猿问

即使在定义函数之后,也会发生错误,并说未定义函数

在javaScript中调用getSavedTodos()之后


发生错误,未捕获ReferenceError:未定义getSavedTodos


即使在定义函数getSavedTodos()之后也会发生错误


我正在使用VS代码


const todos = getSavedTodos()



const filters = {

    search: '',

    hideFalseStates: false

}



const getSavedTodos = function() {

    const todoJSON=localStorage.getItem('todo')

    if(todoJSON !== null) {

        return JSON.parse(todoJSON)

    }

}

不知道错误的发生,代码格式是否有所变化?


慕田峪9158850
浏览 199回答 2
2回答

慕慕森

您的错误是因为在定义函数之前调用了该函数。该代码是从上到下阅读的,因此在定义它之前,不能使用任何变量或函数。const todos = getSavedTodos() //<-- Move this to after you defined the functionconst filters = {&nbsp; &nbsp; search: '',&nbsp; &nbsp; hideFalseStates: false}const getSavedTodos = function(){&nbsp; &nbsp; const todoJSON = localStorage.getItem('todo')&nbsp; &nbsp; if(todoJSON !== null) {&nbsp; &nbsp; &nbsp; &nbsp; return JSON.parse(todoJSON)&nbsp; &nbsp; }}

慕田峪7331174

在定义它之前,您正在使用它。您有两种选择:在使用之前,只需将定义上移至:const getSavedTodos=function(){&nbsp; &nbsp; const todoJSON=localStorage.getItem('todo')&nbsp; &nbsp; if(todoJSON!==null)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return JSON.parse(todoJSON)&nbsp; &nbsp; }}const todos = getSavedTodos()const filters={&nbsp; &nbsp; search: '',&nbsp; &nbsp; hideFalseStates: false}使用函数声明而不是函数表达式,因为它们已被提升(它们在逐步评估代码之前得到评估):const todos = getSavedTodos()const filters={&nbsp; &nbsp; search: '',&nbsp; &nbsp; hideFalseStates: false}function getSavedTodos(){&nbsp; &nbsp; const todoJSON=localStorage.getItem('todo')&nbsp; &nbsp; if(todoJSON!==null)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return JSON.parse(todoJSON)&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答