如何遍历Local Storage中全部来源URL并访问指定位置的URL
解决Local Storage中访问第二/第三个URL的问题
你当前的遍历代码Object.entries(localStorage).forEach(...)理论上会输出Local Storage里所有键值对,如果你只看到第一个URL,大概率是以下两种情况之一,对应不同的解决方式:
情况1:三个URL是独立的键值对
如果Local Storage里是三个分开的键值对(每个key对应一个URL),可以把Object.entries(localStorage)转成数组,通过索引直接访问(数组索引从0开始,第二个对应索引1,第三个对应索引2):
// 把Local Storage的键值对转成数组 const storageItems = Object.entries(localStorage); // 访问第二个URL if (storageItems.length >= 2) { const [_, secondUrl] = storageItems[1]; // 下划线表示不需要key,只取value console.log('第二个URL:', secondUrl); // 跳转到该URL window.location.href = secondUrl; } // 访问第三个URL if (storageItems.length >= 3) { const [_, thirdUrl] = storageItems[2]; console.log('第三个URL:', thirdUrl); window.location.href = thirdUrl; }
情况2:三个URL存在同一个key的value中
如果三个URL是用逗号、分号这类分隔符拼在同一个value里,需要先拆分字符串再访问:
// 替换成存储URL的实际键名 const targetKey = '存储URL的键名'; const urlsStr = localStorage.getItem(targetKey); if (urlsStr) { // 按实际分隔符拆分,比如逗号用',',换行用'\n' const urls = urlsStr.split(','); // 访问第二个URL if (urls.length >= 2) { console.log('第二个URL:', urls[1]); window.location.href = urls[1]; } // 访问第三个URL if (urls.length >= 3) { console.log('第三个URL:', urls[2]); window.location.href = urls[2]; } }
补充验证
如果不确定存储结构,可以先运行这段代码查看完整的Local Storage内容:
console.log('全部Local Storage内容:', localStorage); // 打印所有键值对的序号和内容 Object.entries(localStorage).forEach(([key, value], index) => { console.log(`第${index+1}个: ${key} => ${value}`); })
内容的提问来源于stack exchange,提问作者Adarsh Kumar GM
相关产品推荐
相关产品推荐

