冒号(:)在这个javascript行中的含义是什么?

Cla*_*ols 4 javascript

":"在下面的第3-6行中是什么意思?

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;

}
Run Code Online (Sandbox Code Playgroud)

Mic*_*ski 12

变量errorTypes是一个对象文字.将:对象属性名称(数字)与其值分隔开.如果您熟悉其他语言的哈希表,则此结构是类似的概念.或者在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
Run Code Online (Sandbox Code Playgroud)

请注意,引用对象属性的常规语法(使用点运算符)不适用于这些数字属性:

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

// Instead use the [] notation
errorTypes[0]
Run Code Online (Sandbox Code Playgroud)

在这种情况下,由于使用了数字属性名称,因此可以将整个事物定义为数组,并通过[]符号以完全相同的方式访问,但对键的语法控制较少.

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