如何在LocalStorage存在以指定字符串开头的键时执行代码?
检测LocalStorage中以特定前缀开头的键
你可以通过以下方式实现需求,用filter或更高效的some方法都能完成检测:
方法一:使用filter筛选匹配键
先获取LocalStorage所有键组成的数组,再筛选出以指定前缀开头的键,最后判断是否存在匹配结果:
// 获取localStorage中所有键的数组 const allStorageKeys = Object.keys(localStorage); // 筛选出以"mykey"开头的键 const matchedKeys = allStorageKeys.filter(key => key.startsWith('mykey')); // 存在匹配键时执行代码 if (matchedKeys.length > 0) { document.querySelector("#button").textContent = "hello"; }
方法二:使用some直接判断存在性
如果只需要判断是否存在符合条件的键,some方法会更高效——它找到第一个匹配项后就会停止遍历,无需处理所有键:
if (Object.keys(localStorage).some(key => key.startsWith('mykey'))) { document.querySelector("#button").textContent = "hello"; }
代码说明
Object.keys(localStorage):把LocalStorage里的所有键转换成数组,方便进行筛选/判断操作key.startsWith('mykey'):ES6字符串方法,直接判断当前键是否以指定前缀开头,语法简洁直观
内容的提问来源于stack exchange,提问作者Guru Surfer
相关产品推荐
相关产品推荐

