javascript - 增加计数器值并更新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'))
但我不知道下一步该做什么。逐步解释如何执行此操作
解决方案
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 是同步发生的,如果您经常这样做,这可能会减慢您的应用程序。
推荐阅读
- python - / 不支持的操作数类型:“Vat”和“int”
- git - Git 再次签出仅最初从另一个分支签出的文件
- wpbakery - 如何更改 WP Bakery 中的堆叠行顺序?
- javascript - 我正在尝试使用 puppeteer 在页面上自动登录,一旦我在下一页上登录,我想单击下一页上的按钮
- java - 转换为浮点数/从浮点数转换时 BigDecimal 不保留舍入值
- html - Angular Material:自动缩放元素的高度
- ansible - Ansible - vmware_guest 模块创建 windows 服务器机器
- python - 我如何使用移动平均线的定义,编写 Python 代码(使用 for 循环)来计算一个称为 ma 的 n 周期移动平均线列表?
- javascript - DateTimePicker 的问题以及如何将所选日期传递给另一个函数?
- decentralized-identity - 如何确保可验证的凭证颁发者是合法的颁发者?