What does the “:” mean in the 3-6th lines below?
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;
}
The variable
errorTypesis an object literal. The:separates the object property name (the numbers) from its value. If you are familiar with hash tables in other languages, this structure is a similar concept. Or in PHP, for example, this could be represented as an associative array.You can do:
Note that the normal syntax for referencing an object property (using the dot operator) won’t work for these numeric properties:
In this instance, since numeric property names were used, the whole thing could have been defined as an array instead and accessed exactly the same way via the
[]notation, but with less syntactic control over the keys.