JavaScript中的冒号(:)表示什么? [英] What does the colon (:) in JavaScript represent?

查看:1004
本文介绍了JavaScript中的冒号(:)表示什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个愚蠢的noob问题,但是:在以下背景中代表什么:

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?

推荐答案

这是 object literal [MDN]

var obj = {
    key: value
};

// obj.key === value; // true

它将分配给属性 key obj 虽然对的限制没有限制(好吧,它必须是可分配的东西),但有限制离子:它必须是 标识符名称 ,字符串文字或数字文字。

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.

更多细节可在第11.1.5节

文字符号类似于:

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.

这不起作用:

var obj = {
    foo: value,
    bar: obj.foo
};

而这样做:

var obj = {};
obj.foo = value;
obj.bar = obj.foo;






为了完整性,冒号有两种其他用途在JavaScript中:


For completeness, there are two other uses of colons in JavaScript:

var val = condition ? true-value : false-value;


  • 标签 [MDN]

    someLabel: var x = 5;
    


  • 这篇关于JavaScript中的冒号(:)表示什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆