如何访问js中的属性值?

时间:2017-09-01 02:00:12

标签: javascript

我有一个这样的对象:

   let rates = {AUD: 1.5016, BGN: 1.9558, BRL: 3.741, CAD: 1.497, CHF: 1.1446}

我如何访问每个属性?例如,我试过:

let val ='EUR';
let test = rates[val];

导致test = undefined?

3 个答案:

答案 0 :(得分:0)

您尝试做的是找到EUR属性/值,在您的对象中未定义。你可以做什么,如果你想创建另一个属性(如果我正确理解你)是

rates.EUR = // whatever you want the rate to be

如果那不是你想要做的,请提供更多关于你需要做什么的信息。

答案 1 :(得分:0)

这对你有帮助:

     let rates = {AUD: 1.5016, BGN: 1.9558, BRL: 3.741, CAD: 1.497, CHF: 1.1446}
    You can access in two ways:
     1.  rates.AUD --Result is=1.5016
     2. rates['AUD'] -- Result is=1.5016

in case of you, it was showing undefined because of there is no property('EUR') exist in the above object (rated).

答案 2 :(得分:0)

以下是如何访问对象中每个值的示例。它将向console.log报告密钥和值。 该示例生成对象中存在的键的数组,然后使用forEach()方法仅报告键和值。如果您使用的是单独的密钥列表,则可以使用.hasOwnProperty()方法在尝试访问密钥之前测试对象中是否存在密钥。

let rates = {AUD: 1.5016, BGN: 1.9558, BRL: 3.741, CAD: 1.497, CHF: 1.1446}
// How can I access each property? for example I tried :

let keys = Object.keys(rates);

keys.forEach( key => console.log(`key = ${key}, value = ${rates[key]}`));