2011-12-03 80 views
4

「:」在下面的第3-6行是什麼意思?這個javascript行中的冒號(:)是什麼意思?

function displayError(error) { 
    var errorTypes = { 
     0: "Unknown error", 
     1: "Permission denied", 
     2: "Position is not available", 
     3: "Request timeout" 
    }; 
    var errorMessage = errorTypes[error.code]; 
    if (error.code == 0 || error.code == 2) { 
     errorMessage = errorMessage + " " + error.message; 
    } 
    var div = document.getElementById("location"); 
    div.innerHTML = errorMessage; 

} 
+4

您可能會發現[Eloquent JavaScript](http://eloquentjavascript.net/)值得一讀。 [第4章](http://eloquentjavascript.net/chapter4.html)是關於數據結構的。 – RightSaidFred

+1

@RightSaidFred - 謝謝,這看起來非常好! –

回答

12

可變errorTypesobject literal:從其值中分離出對象屬性名稱(數字)。如果你熟悉其他語言的哈希表,這個結構是一個類似的概念。例如,在PHP中,這可以表示爲關聯數組。

你可以這樣做:

var errorTypes = { 
    0: "Unknown error", 
    1: "Permission denied", 
    2: "Position is not available", 
    3: "Request timeout" 
}; 

console.log(errorTypes[0]); 
// Unknown error 

console.log(errorTypes[2]); 
// Permission denied 

注意,對於引用的對象屬性(使用點運算符)的正常語法不會爲這些數值屬性的作用:

// Won't work for numeric properties 
errorTypes.0 
SyntaxError: Unexpected number 

// Instead use the [] notation 
errorTypes[0] 

在這種情況下,因爲使用了數字屬性名稱,所以可以將整個事物定義爲一個數組,而且通過[]表示法以完全相同的方式進行訪問,但對鍵的語法控制較少。

// As an array with the same numeric keys 
var errorTypes = [ 
    "Unknown error", 
    "Permission denied", 
    "Position is not available", 
    "Request timeout" 
]; 
console.log(errorTypes[2]); 
0

這就是您如何定義對象中的鍵值對。因此errorTypes.2將返回字符串「位置不可用」。

相關問題