object literal
An object literal is a list of 0 or more property name-value pairs (elements) that are enclosed in curly brace pairs ({}). You cannot use object literals at the beginning of a statement, which results in an error or unexpected behavior, because the left curly brace ({) is considered to be the starting symbol for a block of statements.
The following is an example of an object literal. The first element of the object car (i.e., an attribute/value pair) defines the attribute Mycar; the second element, the attribute Getcar, refers to a function (i.e. cartypes ("Honda")), a third element, a property special, An existing variable (that is, sales) is used.
var Sales="Toyota";functionCartypes(Name){Return(Name==="Honda")? Name:"Sorry, we don ' t sell"+ Name+".";}var car={MyCar:"Saturn", Getcar:Cartypes("Honda"), Special: Sales}; console.Log(Car. MyCar);Saturnconsole.Log(Car. Getcar);Hondaconsole.Log(Car. Special);Toyota
Further, you can use a number or string literal as the name of the property, or set a literal value inline in another literal. These options are used in the example below.
var car={Manycars:{A:"Saab","B":"Jeep"},7:"Mazda"};
Consolelog (Car.manycars< Span class= "token punctuation" >.b) //
Jeep console. Log (Car[7]//Mazda
The object property name can be any string, including the empty string. If the object property name is not a valid JavaScript identifier,
It must be wrapped with "". The name of the property is not valid, then it cannot be used. Access and assign values through the class array tag ("[]") instead of accessing the property value.
var unusualpropertynames={"":"An empty string","!":"Bang!"}console.Log(Unusualpropertynames."");Syntax error: unexpected Stringconsole.Log(Unusualpropertynames[""]//an empty Stringconsole. Log (Unusualpropertynames.! //syntax error: unexpected token!console.log[ "!" ]) //bang!
Please note:
var foo={A:"Alpha",2:"Both"}; console.Log(foo. A);Alphaconsole.Log(foo[2])//two//console.log (foo.2);//error:missing) after Argument List//console.log (Foo[a]);//error:a is not Definedconsolelog (Foo[ "a" ]) ; //alphaconsole. Log (Foo[ "2" ]//
javascript--object Literals common notation and rules