Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

javascript - js localStorage for cycle includes empty string

I'm creating site with weather information now. I have a special form (.html file) that adds new city with info as unordered list. I'm also using localStorage to save cities when user refreshed the page by accident.

localStorage stores only string as I know. When user adds new city, script updates localStorage. In order to to refresh the page, refresh button is provided.

When user refreshes the page, all cities are gone, so the script recovers all cities by that localStorage. Array value [] represented as String value "" in JS. The problem is, when the script tries to restore cities, "" value would also provided as city value.

Code:

    let cities = [];
    if (localStorage.getItem("cities") !== null) {
        cities = localStorage.getItem("cities").split(',');
    }
    console.log("cities = " + cities);

    for (const city of cities) {
        if (city !== "" && !screen_cities.includes(city)) {
            const rnd = Math.random().toString();
            const code = await add_new_li(city, rnd);
            if (code === 1) {
                console.warn("for city " + city + " code is " + code);
                document.getElementById(rnd).remove();
            }
        }
    }

Array.prototype.forEach doesn't that, but I can't use it because of asynchronous function add_new_li.

Please help me.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

With JSON.stringfy and JSON.parse, we can save object via localStorage

let cities = [];
if (localStorage.getItem("cities") !== null) {
    cities = JSON.parse(localStorage.getItem("cities"))
}
console.log("cities = " + cities);

for (const city of cities) {
    if (city !== "" && !screen_cities.includes(city)) {
        const rnd = Math.random().toString();
        const code = await add_new_li(city, rnd);
        if (code === 1) {
            console.warn("for city " + city + " code is " + code);
            document.getElementById(rnd).remove();
        }
    }
}

// -------- save
cities.push('Shen Yang')
localStorage.setItem('cities', JSON.stringify(cities))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...