下面第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;
}发布于 2011-12-04 06:57:44
变量errorTypes是一个object 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]);发布于 2011-12-04 06:58:46
这就是在对象中定义键值对的方式。因此,errorTypes.2将返回字符串"Position is not available“。
https://stackoverflow.com/questions/8371718
复制相似问题