简体   繁体   中英

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.

Can someone give me some advice on how I can set the value to 1 if a null is returned from getItem? 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

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

Or you can simply use If/Else

if(storage.getItem('phrasesOrderById') {

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

    this.phrasesOrderById = 1;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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