You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 00:32:06