如何从localStorage的customer键中提取fullname值并填充div元素
解决方法
首先要明确:localStorage里存储的所有数据都是字符串格式,直接用getItem取出的是对象的字符串形式,没法直接访问属性。得先把它转成JS对象,再提取fullname属性。
修改后的完整代码
<div id="results"></div> <script> // 从localStorage取出字符串并转换为JS对象 const customer = JSON.parse(localStorage.getItem('customer')); // 提取fullname属性并插入到页面容器中 document.getElementById('results').innerHTML = customer?.fullname; </script>
额外说明
- 用
JSON.parse()完成字符串到JS对象的转换,这是操作存储对象的关键步骤 - 代码里的
?.是可选链操作符,能避免customer不存在(比如localStorage里没有这个键)时触发报错;要是你确定这个键一定存在,也可以直接写customer.fullname - 如果是你自己往localStorage存对象,存的时候得先用
JSON.stringify()转成字符串,示例代码如下:const customer = { "fullname": "John Doe", "firstname": "John" }; localStorage.setItem('customer', JSON.stringify(customer));
内容的提问来源于stack exchange,提问作者Jerry
相关产品推荐
相关产品推荐

