简体   繁体   English

用变量替换对象文字的属性

[英]Replace the attribute of an object literal by a variable

I have an object literal with a list of countries with two values, price and name: 我有一个对象文字,其中包含具有两个值的国家列表,价格和名称: 在此处输入图片说明

When the select changes I store the values of the current selected country: 当选择更改时,我将存储当前所选国家/地区的值: 在此处输入图片说明

And I store this value in the variable inner function .change(): 我将此值存储在变量内部函数.change()中:

current_country = $('#country').val();

I accessed this way the object literal for example countries_list.deu 我通过这种方式访问​​对象字面量,例如countries_list.deu

But when I use my current_country Variable console shows me what undefined: 但是,当我使用current_country变量控制台时,会向我显示未定义的内容:

 console.log(countries_list.current_country);

How I can fix this? 我该如何解决?

Use selectedIndex to get the selected value index and use .options[i].value to get the value of the option with the following index: 使用selectedIndex获取所选值的索引,并使用.options [i] .value获取具有以下索引的选项的值:

var countries = document.getElementById("country");
var current_country = countries.options[countries.selectedIndex].value;

you should be using bracket notation 您应该使用括号表示法

console.log(countries_list[current_country]);

In your case, it actually looks for the property named current_country within the object, where it doesn't exist. 在您的情况下,它实际上在对象中查找不存在的名为current_country的属性。

Look at this for better understanding of two different notations 查看此内容可以更好地理解两种不同的符号

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

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