简体   繁体   English

如果未返回任何内容,如何将localStorage值设置为数字1?

[英]How can I set a localStorage value to the number 1 if nothing is returned?

Here is what I have tried so far: 到目前为止,这是我尝试过的:

this.phrasesOrderById = 
   parseInt(storage.getItem('phrasesOrderById').toInt(),10) || 1;

However this gives me a message saying cannot read property toInt of null. 但是,这给了我一条消息,提示无法读取null的属性toInt。

Can someone give me some advice on how I can set the value to 1 if a null is returned from getItem? 有人可以给我一些建议,如果从getItem返回null时如何将值设置为1吗? Note that I spread this one line across two as it doesn't seem to display properly when it's just one line. 请注意,我将这一行分布在两行上,因为当仅一行时它似乎无法正确显示。

以下作品

    phrasesOrderById = parseInt(localStorage.getItem("phrasesOrderById") || 1);

you can use the ? 你可以用? : (conditional) operator in JavaScript :JavaScript中的(条件)运算符

this.phrasesOrderById = storage.getItem('phrasesOrderById')?parseInt(storage.getItem('phrasesOrderById').toInt(),10):1;

Or you can simply use If/Else 或者您可以简单地使用If / Else

if(storage.getItem('phrasesOrderById') {

    this.phrasesOrderById = parseInt(storage.getItem('phrasesOrderById').toInt(), 10);
}
else{

    this.phrasesOrderById = 1;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM