简体   繁体   English

如何检索已在关联数组中初始化的值

[英]How to retrieve a value already initialized in an associative array

I wish I didn't have to rewrite some things that could just be copied from a variable in an associative array created.我希望我不必重写一些可以从创建的关联数组中的变量复制的东西。

That is my code, but I got an error that says title is not defined :那是我的代码,但我收到一个错误,提示标题未定义

const shopLocation = {
  "uccle-heros": {
    title: "Uccle Héros Defré",
    location: [4.334562, 50.043438],
    description: '<strong>'
      + 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>'
  }
};

You need to use a getter :您需要使用吸气剂

 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 pm</p>' } } }; console.log(shopLocation)

In addition to @Spectric's answer , use interpolated strings .除了@Spectric 的答案,使用插值字符串 Much more readable:更具可读性:

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>`
    }
  }
};

console.log(shopLocation)

Ok first of this is called an object in javascript好的,首先在 javascript 中称为 object

secondly in order to reference something nested in a nested object like this you have to call it as such shopLocation['uccle-heros'].title其次,为了引用嵌套在像这样的嵌套 object 中的东西,你必须这样称呼它shopLocation['uccle-heros'].title

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM