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

后端 未结 2 1410
长发绾君心
长发绾君心 2021-01-06 08:27

What does the \":\" mean in the 3-6th lines below?

function displayError(error) {
    var errorTypes = {
        0: \"Unknown error\",
        1: \"Permissi         


        
相关标签:
2条回答
  • 2021-01-06 08:39

    That's how you define key value pairs in an object. So errorTypes.2 would return the string "Position is not available".

    0 讨论(0)
  • 2021-01-06 08:48

    The variable errorTypes is 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:

    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) won't work for these numeric properties:

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

    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.

    // 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 讨论(0)
提交回复
热议问题