Object as data type
Access properties
Delete properties
Syntax of property names
Object usage and properties
All variables in JavaScript can be used as objects, with two exceptions null and undefined .
false.toString(); // 'false' [1, 2, 3].toString(); // '1,2,3' function Foo(){} Foo.bar = 1; Foo.bar; // 1
A common misunderstanding is that numerical literals cannot be used as objects. This is due to a bug in the JavaScript parser, which attempts to parse dot operators as part of a floating-point literal value.
2.toString(); // 出错:SyntaxError
There are many workarounds to make number literals look like objects.
2..toString(); // 第二个点号可以正常解析 2 .toString(); // 注意点号前面的空格 (2).toString(); // 2先被计
Objects as data types
JavaScript objects can be used as hash tables, mainly used to save the correspondence between named keys and values.
Using the object literal syntax - {} - you can create a simple object. This newly created object inherits from Object.prototype and does not have any custom properties.
var foo = {}; // 一个空对象 // 一个新对象,拥有一个值为12的自定义属性'test' var bar = {test: 12};
Access properties
There are two ways to access the properties of an object, the dot operator or the square bracket operator.
var foo = {name: 'kitten'} foo.name; // kitten foo['name']; // kitten var get = 'name'; foo[get]; // kitten foo.1234; // SyntaxError foo['1234']; // works
The two syntaxes are equivalent, but the bracket operator is still valid in the following two situations
Dynamic setting of attributes
The attribute name is not a valid variable name (Translator's Note: For example, the attribute name contains spaces, or the attribute name is a JS keyword)
Delete attribute
The only way to delete an attribute is to use the delete operator; setting the attribute to undefined or null does not actually delete the attribute, but only removes the association between the attribute and the value.
var obj = { bar: 1, foo: 2, baz: 3 }; obj.bar = undefined; obj.foo = null; delete obj.baz; for(var i in obj) { if (obj.hasOwnProperty(i)) { console.log(i, '' + obj[i]); } }
The above output has bar undefined and foo null - only baz is actually deleted, so it disappears from the output.
Syntax of attribute names
var test = { 'case': 'I am a keyword so I must be notated as a string', delete: 'I am a keyword too so me' // 出错:SyntaxError };
The attribute names of objects can be declared using strings or ordinary characters. However, due to another incorrect design of the JavaScript parser, the second declaration method above will throw a SyntaxError before ECMAScript 5.
The reason for this error is that delete is a keyword in the JavaScript language; therefore, in order to run normally under lower versions of JavaScript engines, string literal declaration must be used.
The above is the JavaScript advanced series - object usage and attributes. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!