When to use “:”(colon) operator in javascript vs “

2020-03-01 20:02发布

I tried looking online everywhere for past hour, but I can't seem to figure out when to use colon operator : vs = operator in javascript? From what I can tell so far, it seems when defining object properties use colon :.

3条回答
Viruses.
2楼-- · 2020-03-01 20:39

The JavaScript language was built by Brandon Eich using the = sign as an assignment operator. Back in 1995, most programming languages, like Basic, Turbo Pascal, Delphi, C, C++, etc... used the same method of assigning values to variables.

Rapidly creating new objects in JavaScript using colons : became popular because of Douglas Crockford's work in defining the JSON specification. JSON is easier-to-write & more compact than XML. The JSON.parse() method removes the need to build a client-side XML parser. As a result, JSON is also faster to code than XML. Thus JSON become popular as a data transfer format between servers & client browsers.

If you look at the http://www.json.org you can see how new objects can be written quickly using a {"key1": value1, "key2": value2} pair notation. The use of the colon : is simply shorthand notation for writing longhand object properties, which use the equal sign = as the operator.

Longhand JavaScript Example: (73 characters)

let myObject = new Object();
myObject.a = 1;
myObject.b = 2;
myObject.c = 3;

Shorthand JSON Example: (42 characters)

let myObject = {
  "a": 1,
  "b": 2,
  "c": 3
};

Minified examples:

let myObject=new Object();myObject.a=1;myObject.b=2;myObject.c=3; (65 characters)
let myObject={'a':1,'b':2,'c':3}; (33 characters with quotes, 27 characters without)

You can use equals = or colons : in your code. There isn't any rule, nor best practice about which one is preferred. They can be used together in the same line of code.

let myObject = {a:1, b:2, c:3};

Wikipedia adds more context about JSON, with their JSON page.

查看更多
冷血范
3楼-- · 2020-03-01 20:56

The colon(:) operator as you correctly stated, is used to define an object property:

var object = {
  property:value
}

The equals(=) operator is used to assign values to something, a variable, an array etc.

If you only defined your object as:

var object = {}

You could assign properties to it like this:

object.property = value;
查看更多
我命由我不由天
4楼-- · 2020-03-01 21:00

When you are defining an object, you can use the : notation for defining values of properties.

var obj = { test: "value" };

The = operator is used for defining variable values. As in the above example the variable obj is equal to that object.

Pay attention that you can define object properties also using the = operator.

var obj = {};
obj.test = "value";

Or

obj["test"] = "value";
查看更多
登录 后发表回答