Data type - object

Table of contents

 3. Object

1 Overview

1).Generation method

2).Key name

3).Reference of object

4). Expression or statement

2. Operation of attributes

1).Reading of attributes

2).Assignment of attributes

3).View attributes

4).Deletion of attributes: delete command

5). Whether the attribute exists: in operator

6).Attribute traversal: for...in loop

3.with statement


 3. Object

1 Overview

1).Generation method

An object is a collection of "key-value pairs" and is an unordered composite data collection.

var obj = {
  foo: 'Hello',
  bar: 'World'
};

2).Key name

All key names of objects are strings (ES6 introduced Symbol values ​​that can also be used as key names), so they can be added or not in quotes.

If the key name does not meet the conditions of the identification name (for example, the first character is a number, or contains a space or operator), and it is not a number, you must add quotation marks, otherwise an error will be reported.

// 报错
var obj = {
  1p: 'Hello World'
};

// 不报错
var obj = {
  '1p': 'Hello World',
  'h w': 'Hello World',
  'p+q': 'Hello World'
};

Each key name of an object is also called a "property", and its "key value" can be any data type. If the value of an attribute is a function, the attribute is usually called a "method" and it can be called like a function.

var obj = {
  p: function (x) {
    return 2 * x;
  }
};

obj.p(1) // 2

The attributes of the object are separated by commas, and a comma (trailing comma) may or may not be added after the last attribute.

3).Reference of object

 

4). Expression or statement

{ foo: 123 }

When the JavaScript engine reads the above line of code, it will find that it may have two meanings. The first possibility is that this is an expression that represents an object containing the foo attribute; the second possibility is that this is a statement that represents a code block with a label < /span>. foo, points to expression123

In order to avoid this ambiguity, the JavaScript engine's approach is that if it encounters this situation and cannot determine whether it is an object or a code block, it will always be interpreted as a code block.

{ console.log(123) } // 123

The above statement is a code block and can only be executed if it is interpreted as a code block.

If you want to interpret it as an object, it's better to put parentheses before the curly braces. Because the inside of the parentheses can only be expressions, make sure that the curly braces can only be interpreted as objects.

({ foo: 123 }) // 正确
({ console.log(123) }) // 报错

This difference is most obvious in theeval statement (which evaluates a string).

eval('{foo: 123}') // 123
eval('({foo: 123})') // {foo: 123}

In the above code, if there are no parentheses,eval will understand it as a code block; after adding parentheses, it will understand it as an object.

2. Operation of attributes

1).Reading of attributes

There are two ways to read the properties of an object, one is to use the dot operator, and the other is to use the square bracket operator.

var obj = {
  p: 'Hello World'
};

obj.p // "Hello World"
obj['p'] // "Hello World"

 If you use the square bracket operator, the key name must be placed in quotes, otherwise it will be treated as a variable.

Expressions can also be used inside the square bracket operator. Numeric keys do not need to be quoted, as they will be automatically converted into strings.

Numeric key names cannot use the dot operator (because it will be treated as a decimal point), only the square bracket operator can be used.

2).Assignment of attributes

The dot operator and square bracket operator can be used not only to read values, but also to assign values.

3).View attributes

To view all properties of an object itself, you can use the Object.keys method.

var obj = {
  key1: 1,
  key2: 2
};

Object.keys(obj);
// ['key1', 'key2']

4).Deletion of attributes: delete command

deleteThe command is used to delete the attributes of an object and returnstrue after the deletion is successful.

Delete a non-existent attribute,delete does not report an error, and returnstrue.

var obj = { p: 1 };
Object.keys(obj) // ["p"]

delete obj.p // true
obj.p // undefined
Object.keys(obj) // []

There is only one case in which the delete command will returnfalse, that is, the attribute exists and cannot be deleted.

deleteThe command can only delete the attributes of the object itself, but cannot delete inherited attributes.

5). Whether the attribute exists: in operator

inThe operator is used to check whether the object contains a certain attribute (checking the key name). If it does, it returns true, otherwise it returns false. On the left is a string representing the attribute name, and on the right is an object.

var obj = { p: 1 };
'p' in obj // true
'toString' in obj // true

It cannot identify which properties are the object's own and which properties are inherited.

You can use the object'shasOwnProperty method to determine whether it is an attribute of the object itself.

var obj = {};
if ('toString' in obj) {
  console.log(obj.hasOwnProperty('toString')) // false
}

6).Attribute traversal: for...in loop

for...inLoops are used to iterate through all properties of an object.

var obj = {a: 1, b: 2, c: 3};

for (var i in obj) {
  console.log('键名:', i);
  console.log('键值:', obj[i]);
}
// 键名: a
// 键值: 1
// 键名: b
// 键值: 2
// 键名: c
// 键值: 3

for...inThere are two points to note when using loops.

  • It traverses all enumerable properties of the object and skips non-traversable properties.
  • It not only traverses the properties of the object itself, but also the inherited properties.

Objects all inherit thetoString attribute, but the for...in loop will not traverse this attribute. Because it is "non-traversable" by default.

If the inherited attribute is traversable, it will be traversed byfor...in loop. Generally speaking, you only want to traverse the properties of the object itself, and you should use the hasOwnPropertymethod in combination.

var person = { name: '老张' };

for (var key in person) {
  if (person.hasOwnProperty(key)) {
    console.log(key);
  }
}
// name

3.with statement

Its function is to provide some writing convenience when operating multiple properties of the same object.

// 例一
var obj = {
  p1: 1,
  p2: 2,
};
with (obj) {
  p1 = 4;
  p2 = 5;
}
// 等同于
obj.p1 = 4;
obj.p2 = 5;

// 例二
with (document.links[0]){
  console.log(href);
  console.log(title);
  console.log(style);
}
// 等同于
console.log(document.links[0].href);
console.log(document.links[0].title);
console.log(document.links[0].style);

Ifwith there is a variable assignment operation inside the block, it must be an existing attribute of the current object, otherwise a global variable of the current scope will be created.

var obj = {};
with (obj) {
  p1 = 4;
  p2 = 5;
}

obj.p1 // undefined
p1 // 4

This is becausewith the block has not changed the scope, and its interior is still the current scope. This causes a big drawback of the with statement, which is that the binding object is unclear.

with (obj) {
  console.log(x);
}

Simply from the above code block, it is impossible to determine whetherx is a global variable or an attribute of the objectobj. This is very unfavorable for code debugging and modularization. The compiler cannot optimize this code and can only leave it to runtime judgment, which slows down the running speed. Therefore, it is recommended not to use the with statement. You can consider using a temporary variable instead of with.

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/lxlsygxs2017/article/details/113744246