使用变量访问 Javascript 中的对象信息

Accessing Object information in Javascript with a variable?

本文关键字:对象 信息 Javascript 变量 访问      更新时间:2023-09-26

我似乎不了解如何正确访问对象值。

我的对象:

  // countrycode: "Radio station name"
  var radioStations = {
    fi: "Foo",
    hu: "Bar",
    am: "Baz"
  };

然后我有一个名为 code 的变量,它来自 jQuery 插件,并具有用户将鼠标悬停在矢量地图上的国家/地区的国家/地区代码。

我需要使用code将广播电台名称添加到此处的工具提示中:

onLabelShow: function(event, label, code){
  if ( code in radioStations ) {
    label.text(radioStations.code); // <- doesn't work
  } else  { // hide tooltips for countries we don't operate in
    event.preventDefault();
  }
},

您需要使用数组表示法才能通过变量访问对象。试试这个:

onLabelShow: function(event, label, code){
    if (code in radioStations) {
        label.text(radioStations[code]);
    } 
    else  { 
        event.preventDefault();
    }
},

示例小提琴

您可以使用:

onLabelShow: function(event, label, code){
  if(radioStations[code]) {
   label.text(radioStations[code]);
  } else {
   event.preventDefault();
  }
}

演示