JavaScript 中的冒号 (:) 代表什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7147273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does the colon (:) in JavaScript represent?
提问by Felix Kling
This is probably a stupid noob question but what does the : represent in the following context:
这可能是一个愚蠢的菜鸟问题,但是 : 在以下上下文中代表什么:
var stuffToDo = {
'bar' : function() {
alert('the value was bar -- yay!');
},
'baz' : function() {
alert('boo baz :(');
},
'default' : function() {
alert('everything else is just ok');
}
};
if (stuffToDo[foo]) {
stuffToDo[foo]();
} else {
stuffToDo['default']();
}
Is it storing the function to each of those variables?
是否将函数存储到每个变量中?
回答by Felix Kling
This is an object literal[MDN]:
这是一个对象文字[MDN]:
var obj = {
key: value
};
// obj.key === value; // true
It assigns value
to a property key
of obj
. While there are no restriction for what value
can be (well, it must be something assignable), there are limitations for key
: It must be either an identifier name, a string literal or a numeric literal.
它指定value
一个属性key
的obj
。虽然对value
可以是什么没有限制(好吧,它必须是可分配的),但有以下限制key
:它必须是标识符名称、字符串文字或数字文字。
More details can be found in section 11.1.5of the ECMAScript specification.
更多细节可以在 ECMAScript 规范的11.1.5 节中找到。
The literal notation is similar to:
文字符号类似于:
var stuffToDo = {}; // <-- empty object literal
stuffToDo.bar = function() {...};
// or stuffToDo['bar'] = ...
stuffToDo.baz = function() {...};
// or stuffToDo['baz'] = ...
The biggest difference is that when using an object literal, you cannot access other properties of the object during the declaration.
最大的区别是,在使用对象字面量时,您不能在声明期间访问对象的其他属性。
This will not work:
这将不起作用:
var obj = {
foo: value,
bar: obj.foo
};
whereas this does:
而这样做:
var obj = {};
obj.foo = value;
obj.bar = obj.foo;
For completeness, there are two other uses of colons in JavaScript:
为了完整起见,JavaScript 中还有两种冒号的用法:
Conditional (ternary) operator [MDN]:
var val = condition ? true-value : false-value;
someLabel: var x = 5;
var val = condition ? true-value : false-value;
someLabel: var x = 5;
回答by gearsdigital
It is the object literal notationhttp://www.dyn-web.com/tutorials/obj_lit.php