2017-09-01 103 views
-3

我有一個這樣的對象:如何訪問js中的屬性值?

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?

+1

'EUR'不可用率對象。 –

+1

您在示例中顯示的數據中沒有「EUR」值? –

+1

'歐元'不在您的樣本集中。這是你的代碼的情況,還是一個示例設置問題? – Sablefoste

回答

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

0

你試圖做的是找到你的對象中未定義的EUR屬性/值。你可以做什麼,如果你想創建另一個屬性(如果我正確認識你)是

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

如果這是你想要做的,提供爲你所需要的更多信息,並不什麼完成。

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).