如何在关联数组中引用已初始化属性值 解决属性未定义报错
报错原因
在对象字面量的定义过程中,无法直接引用同一对象下的其他属性。此时uccle-heros对应的对象还未完成初始化,title既不是当前作用域下可访问的独立变量,也无法在字面量声明阶段直接通过对象属性调用,因此会抛出title is not defined的错误。
解决方案
方法1:提取公共变量复用
将需要复用的内容提前定义为外部变量,再分别赋值给对象对应的属性,逻辑简单直观:
// 提前定义要复用的门店名称 const shopTitle = "Uccle Héros Defré"; const shopLocation = { "uccle-heros": { title: shopTitle, location: [4.334562, 50.043438], description: '<strong>' + shopTitle + '</strong>' + '<p>' + '<a id="test" ' + 'href="http://www.mtpleasantdc.com/makeitmtpleasant" ' + 'target="_blank" ' + 'title="Opens in a new window">' + 'Make it Mount Pleasant</a>' + 'is a handmade and vintage market and afternoon of live ' + 'entertainment and kids activities. 12:00-6:00 p.m.' + '</p>' } };
方法2:用getter方法实现动态读取
通过对象的getter语法定义description,调用时会自动读取当前对象的title属性,不需要修改原有调用逻辑:
const shopLocation = { "uccle-heros": { title: "Uccle Héros Defré", location: [4.334562, 50.043438], get description() { return '<strong>' + this.title + '</strong>' + '<p>' + '<a id="test" ' + 'href="http://www.mtpleasantdc.com/makeitmtpleasant" ' + 'target="_blank" ' + 'title="Opens in a new window">' + 'Make it Mount Pleasant</a>' + 'is a handmade and vintage market and afternoon of live ' + 'entertainment and kids activities. 12:00-6:00 p.m.' + '</p>' } } };
使用时和普通属性没有区别,直接调用shopLocation["uccle-heros"].description即可拿到拼接完成的字符串。
方法3:分阶段赋值
先完成对象基础属性的初始化,再单独给description赋值,此时对象已经创建完成,可以直接读取内部属性:
const shopLocation = { "uccle-heros": { title: "Uccle Héros Defré", location: [4.334562, 50.043438] } }; // 单独补全description属性 shopLocation["uccle-heros"].description = '<strong>' + shopLocation["uccle-heros"].title + '</strong>' + '<p>' + '<a id="test" ' + 'href="http://www.mtpleasantdc.com/makeitmtpleasant" ' + 'target="_blank" ' + 'title="Opens in a new window">' + 'Make it Mount Pleasant</a>' + 'is a handmade and vintage market and afternoon of live ' + 'entertainment and kids activities. 12:00-6:00 p.m.' + '</p>';
内容的提问来源于stack exchange,提问作者forcela
相关产品推荐
相关产品推荐

