簡體   English   中英

如何檢索已在關聯數組中初始化的值

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

我希望我不必重寫一些可以從創建的關聯數組中的變量復制的東西。

那是我的代碼,但我收到一個錯誤,提示標題未定義

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

您需要使用吸氣劑

 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)

除了@Spectric 的答案,使用插值字符串 更具可讀性:

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)

好的,首先在 javascript 中稱為 object

其次,為了引用嵌套在像這樣的嵌套 object 中的東西,你必須這樣稱呼它shopLocation['uccle-heros'].title

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM