从函数调用 JSON.parse 返回 Undefined

太空人

我需要将 JSON 存储在变量中。我有下一个功能:

retrieve(){
    JSON.parse(localStorage.getItem('todos'));
}

我试图将函数的返回值存储在变量中。

this.todos = this.retrieve()

但我得到:

model.js:5 未捕获的类型错误:无法读取未定义的属性“检索”

如果我这样做,它会起作用:

this.todos = JSON.parse(localStorage.getItem('todos'));

为什么会这样?

编辑:完整代码

export default class Model {

constructor(){
    this.view = null;
    this.todos = this.retrieve();
    if(!this.todos || this.todos.length < 1){
        this.todos = [
            {
                id: 0,
                title: 'default',
                description: 'default',
                completed: false,
            }
        ]
        this.id = 1;
    }
    this.id = this.todos[this.todos.length - 1].id + 1;

    retrieve(){
         return JSON.parse(localStorage.getItem('todos'));
    }

}

谢谢大家。

拉杰迪普·德布纳特

您的类级方法应该在构造函数之外。

localStorage.setItem('todos', JSON.stringify([{id:1},{id:2},{id:3}]))

class Model {

constructor(){
    this.view = null;
    this.todos = this.retrieve();
    if(!this.todos || this.todos.length < 1){
        this.todos = [
            {
                id: 0,
                title: 'default',
                description: 'default',
                completed: false,
            }
        ]
        this.id = 1;
    }
    this.id = this.todos[this.todos.length - 1].id + 1;

}



    retrieve(){
         return JSON.parse(localStorage.getItem('todos'));
    }
}

console.log(new Model());

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用函数“parse-json”进行转换返回错误

undefined 从函数返回

Webscraper 函数返回 undefined

函数在字符串中调用后返回 undefined

循环期间的函数调用错误地返回undefined

为什么在箭头函数中引用时“ this”返回“ undefined”,而在匿名函数中调用时为何不返回“ undefined”?

如何从 div 调用函数并呈现返回的 json 对象?

带有reviver函数的JSON.parse返回未定义

JSON.parse 返回意外令牌

JSON.parse()返回意外令牌

如何避免JSON.stringify在特殊情况下返回undefined,并以这种方式为JSON.parse创建失败的字符串?

多个函数调用:'then is undefined'

如何停止返回json_encode的undefined

JSON.Stringify()返回undefined而不是文本

Json 数据返回 undefined 即使它存在

SAPUI5:如果在 setModel 的同一函数中调用,则 getModel 返回 undefined

postgres从函数返回json

从函数返回json数据

从XMLHttpRequest函数返回JSON

如何返回对调用函数的响应?(Android-App 通过 JSON 调用 Java REST-Server)

HttpClient返回json一次,然后返回undefined

为什么函数 getSafestCountriesNames() 在我调用它时返回 promise{pending} 而当我使用 async/await 时它返回 undefined?

调用返回的函数

调用函数返回 Promise

尝试通过调用使用 axios 的函数(异步)来填充数组,该函数在填充数组之前返回 undefined

JS回调返回undefined不是函数

对于每个在html中返回undefined的函数

为什么这个 find 函数返回 undefined?

resolve()函数在promise中返回undefined