2017-02-14 78 views
0

所以當我學習JavaScript我打算問一噸的問題瞭解對象

通常我瞭解變量賦值工作,但是這個代碼是有點混亂,爲什麼OBJ [B] =「Hello World」的?

var obj = { 
    a: "hello world", 
    b: 42 
}; 

var b = "a" ; 

obj[b]; // "hello world" < why is this Hello world? 
obj["b"]; // 42 
+2

因爲您正在訪問'a'屬性...? – Li357

回答

2
var obj = { 
    a: "hello world", 
    b: 42 
}; 

var b = "a" ; // this creates a new variable with string value "a" 

obj[b]; // this references the object property having the string value of 
     // variable b, which is "a" 
+0

我明白了,這非常有趣謝謝你。它如何知道b =「a」;可能指的是物體內部還是無所謂?這是一個很棒的技巧 – Shire

+0

對象鍵被引用爲字符串(帶引號)或變量(不帶)。 – isherwood

2

obj[b]相當於obj['a']因爲你指定的'a'

在JavaScript變量b的值,就可以訪問對象屬性等的使用陣列括號符號(由Andrew提到的)如上述或使用點符號obj.a

2

[]符號允許動態地訪問對象中的屬性/方法。

讓說你有這個dictionnary:

var dict = { 
    foo : "bar", 
    hello : "world" 
}; 

function access(obj, property){ 
    return obj[property]; 
}; 

console.log(access(dict, "hello"));//world 

你不能做到這一點與點符號。