我正在学习 JavaScript,在浏览 jQuery 库时,我发现:
(冒号)被大量使用。这在 JavaScript 中是做什么用的?
// Return an array of filtered elements (r)
// and the modified expression string (t)
return { r: r, t: t };
我正在学习 JavaScript,在浏览 jQuery 库时,我发现:
(冒号)被大量使用。这在 JavaScript 中是做什么用的?
// Return an array of filtered elements (r)
// and the modified expression string (t)
return { r: r, t: t };
var o = {
r: 'some value',
t: 'some other value'
};
在功能上等同于
var o = new Object();
o.r = 'some value';
o.t = 'some other value';
而且,冒号可用于标记语句。例如
var i = 100, j = 100;
outerloop:
while(i>0) {
while(j>0) {
j++
if(j>50) {
break outerloop;
}
}
i++
}
你们忘记了冒号也用于三元运算符(尽管我不知道 jquery 是否为此目的使用它)。
三元运算符是 if/then 语句的表达式形式(表达式返回值)。它是这样使用的:
var result = (condition) ? (value1) : (value2) ;
三元运算符也可用于产生副作用,就像 if/then 一样,但这是非常糟糕的做法。
':' 基本上是键值对的分隔符。在您的示例中,它是 Javascript Object Literal 表示法。
在 javascript 中,对象是用冒号分隔属性的标识符及其值来定义的,因此您可以拥有以下内容:
return {
Property1 : 125,
Property2 : "something",
Method1 : function() { /* do nothing */ },
array: [5, 3, 6, 7]
};
然后像这样使用它:
var o = {
property1 : 125,
property2 : "something",
method1 : function() { /* do nothing */ },
array: [5, 3, 6, 7]
};
alert(o.property1); // Will display "125"
其中的一个子集也称为 JSON(Javascript 对象表示法),它在 AJAX 调用中很有用,因为它在服务器端语言中紧凑且快速解析,并且 Javascript 可以轻松地将 JSON 字符串反序列化为对象。
// The parenthesis '(' & ')' around the object are important here
var o = eval('(' + "{key: \"value\"}" + ')');
如果键包含某种特殊字符或空格,您也可以将键放在引号内,但我不建议这样做,因为它只会使事情更难处理。
请记住,JavaScript语言中的JavaScript Object Literal Notation与用于消息传递的 JSON 标准不同。两者之间的主要区别在于函数和构造函数不是JSON 标准的一部分,但在 JS 对象文字中是允许的。
它是对象字面量语法的一部分。基本格式为:
var obj = { field_name: "field value", other_field: 42 };
然后您可以通过以下方式访问这些值:
obj.field_name; // -> "field value"
obj["field_name"]; // -> "field value"
您甚至可以将函数作为值,基本上为您提供对象的方法:
obj['func'] = function(a) { return 5 + a;};
obj.func(4); // -> 9