2 回答

TA貢獻1856條經(jīng)驗 獲得超17個贊
您的錯誤是因為在定義函數(shù)之前調(diào)用了該函數(shù)。該代碼是從上到下閱讀的,因此在定義它之前,不能使用任何變量或函數(shù)。
const todos = getSavedTodos() //<-- Move this to after you defined the function
const filters = {
search: '',
hideFalseStates: false
}
const getSavedTodos = function(){
const todoJSON = localStorage.getItem('todo')
if(todoJSON !== null) {
return JSON.parse(todoJSON)
}
}

TA貢獻1828條經(jīng)驗 獲得超13個贊
在定義它之前,您正在使用它。
您有兩種選擇:
在使用之前,只需將定義上移至:
const getSavedTodos=function(){
const todoJSON=localStorage.getItem('todo')
if(todoJSON!==null)
{
return JSON.parse(todoJSON)
}
}
const todos = getSavedTodos()
const filters={
search: '',
hideFalseStates: false
}
使用函數(shù)聲明而不是函數(shù)表達式,因為它們已被提升(它們在逐步評估代碼之前得到評估):
const todos = getSavedTodos()
const filters={
search: '',
hideFalseStates: false
}
function getSavedTodos(){
const todoJSON=localStorage.getItem('todo')
if(todoJSON!==null)
{
return JSON.parse(todoJSON)
}
}
添加回答
舉報