首页 > 解决方案 > 增加计数器值并更新localStorage中的数据

问题描述

在 localStorage 中,“counters”键包含一个 JSON 对象,其字段是计数器的名称,其值是计数器的数值。编写 incrementCounter 函数,该函数传入 counterName——计数器的名称作为第一个参数。

该函数的任务是将counterName计数器值加1,并更新localStorage中的数据。LocalStorage 可能包含无效的 JSON,读取可能会导致错误。在这种情况下,函数应该写入新数据,其中指定的计数器的值为 1。最后,函数应该在递增后返回计数器值。

使用示例:

// in localStorage 1 counter: bannerClick = 5
     incrementCounter('bannerClick'); // 6
     incrementCounter('bannerClose'); // 1
// in localStorage 2 counter: bannerClick = 6, bannerClose = 1

帮助执行任务。我只懂怎么解析

   function incrementCounter(counterName){
   const newObj = JSON.parse(localStorage.getItem('counters'))

但我不知道下一步该做什么。逐步解释如何执行此操作

标签: javascriptlocal-storage

解决方案



function incrementCounter(counterName){
    // Initialize a variable to store the counters object
    let counters;

    // Safely try to parse the data in localstorage
    try {
        counters = JSON.parse(localStorage.getItem("counters"));
    } catch (er) {
        // In case localstorage doesn't have a valid JSON make a new object
        counters = {};
    }

    if(typeof counters[counterName] !== 'number'){
        // if the counter is not initialized in the object, initialize it
        counters[counterName] = 0;
    }

    // Now we can safely increment its value in the counters object
    counters[counterName]++;

    // Now that the value is updated, store it back in localStorage
    localStorage.setItem("counters", JSON.stringify(counters));

    // Return the updated value of the counter in question
    return counters[counterName];
}
    

如果您在生产中使用它,我建议您不要使用这种方法,因为访问 localStorage 是同步发生的,如果您经常这样做,这可能会减慢您的应用程序。


推荐阅读