What does the colon (:) mean in this javascript line?

What does the ":" mean in 3-6 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; } 
+4
source share
2 answers

The variable errorTypes is an object literal . : Separates the property name of an object (number) from its value. If you are familiar with hash tables in other languages, this structure is a similar concept. For example, in PHP it can be represented as an associative array.

You can do:

 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 

Note that the normal syntax for referencing an object property (using the dot operator) will not work for these numerical properties:

 // Won't work for numeric properties errorTypes.0 SyntaxError: Unexpected number // Instead use the [] notation errorTypes[0] 

In this case, since numeric property names were used, all of this could be defined as an array instead and accessed in exactly the same way using the [] notation, but with less syntactic control over the keys.

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

The way you define key value pairs in an object. Therefore, errorTypes.2 will return the line "Position not available".

0
source

Source: https://habr.com/ru/post/1384516/


All Articles