1. Let and const commands
1.1 let command
Basic usage
The new let command in ES6 is used to declare variables. It is used in a similar way to var, but the declared variables are only valid within the code block in which the let command is located
{
let a = 11;
var b = 22;
console.log(a) / / 11
console.log(b)
}
console.log(b) / / 22
console.log(a) //ReferenceError: a is not defined.
Copy the code
In the above code quick, two variables were declared with let and var respectively, and these two variables were printed inside and outside the code block respectively. It can be seen from the results that variables declared with let inside the code block can be printed, while variables declared with let outside the code block are referenced incorrectly. Variables declared with var will print correctly both inside and outside the code block, indicating that let variables are valid only in the code block in which they are declared.
Use skills
In a for loop, the let command is a good fit
for (let i = 0; i < 10; i++) {
}
console.log(i) //ReferenceError: i is not defined
Copy the code
The above I is declared using let and is only valid in the for body
/ / a
var a = [];
for (let i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
};
}
a[6] ()/ / 6
/ / two cases
var a = [];
for (var i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
};
}
a[6] ()/ / 10
Copy the code
In example 1 above, I is declared with let, the declared variable is valid only in the block-level scope, and the final output is 6.
Example 2: the variable I is declared by var and is globally valid. So each time, the new value of I overwrites the old value, resulting in the output of the last value of I
Differences between let and VAR
1. There is no variable promotion in the variables declared by let, while there is variable promotion in the variables declared by var
console.log(b) //undefined
console.log(a) //ReferenceError: a is not defined
let a = 11;
var b = 22;
Copy the code
2. Variables declared by let have “temporary dead zones” (TDZ)
ES6 explicitly states that if there are let and const commands in a block, the variables declared by the block to those commands form a closed scope from the start. Any time these variables are used before declaration, an error is reported.
ES6 makes it clear that temporary dead zones and let and const statements do not promote variables. The main purpose of ES6 is to reduce runtime errors and prevent the variable from being used before it is declared, resulting in unexpected behavior
var str = "aaa"
if (true) {
//TDZ start
str = "bbb" //ReferenceError
let str; //TDZ end
console.log(str);
}
Copy the code
In the code above, the variable STR is in the “dead zone” until the let command declares it. STR can be reassigned after the “temporary dead zone” is over
3. The let command cannot be repeated
Let does not allow the same variable to be declared twice in the same scope
/ / a
function f() {
let a = 10;
let a = 1; //SyntaxError: Identifier 'a' has already been declared
}
f()
/ / two cases
function f() {
var a = 1;
let a = 10; //SyntaxError: Identifier 'a' has already been declared
}
f()
Copy the code
From the above, it follows that you cannot redeclare parameters inside a function.
/ / a
function func(arg) {
let arg; / / an error
}
/ / two cases
function func(arg) {{let arg; / / is not an error}}Copy the code
4. The let command adds block-level scope to JavaScript
function f1() {
let n = 5;
if (true) {
let n = 10;
console.log(n); / / 10
}
console.log(n); / / 5
}
f1()
Copy the code
The above function has two code blocks, both declaring variable n. According to the output, the inner and outer code blocks do not affect each other.
1.2 const command
Basic usage
1. Cosnt declares a read-only constant. Once declared, the value of the constant cannot be changed
const PI = 3.1415;
PI / / 3.1415
PI = 3;
// TypeError: Assignment to constant variable.
Copy the code
2. A variable declared by const must not change its value, which means that a const, once declared, must be initialized immediately and cannot be left for later assignment.
const foo;
// SyntaxError: Missing initializer in const declaration
Copy the code
3. Const has the same scope as let: it is only valid in the block-level scope in which the declaration is made.
if (true) {
const MAX = 5;
}
console.log(MAX) //ReferenceError: MAX is not defined
Copy the code
4. Constants declared by the const command are also not promoted and also have temporary dead zones, which can only be used after the declared position.
if (true) {
console.log(MIN) //ReferenceError: MIN is not defined
const MIN = 5;
}
Copy the code
5. Const constants, like let, cannot be declared repeatedly.
var message = "Hello!";
let age = 25;
// The following two lines will return an error
const message = "Goodbye!";
const age = 30;
Copy the code
2. Destruct assignment of variables
2.1 Array deconstruction assignment
Basic usage
ES6 allows extracting values from arrays and objects and assigning values to variables in a pattern called Destructuring.
Before assigning a value to a variable, you had to specify the value directly
var arr = [1.2.3]
var a = arr[0]
var b = arr[1]
var c= arr[2]
console.log(a) / / 1
console.log(b) / / 2
console.log(c) / / 3
Copy the code
ES6 allows you to write the following to indicate that you can extract values from an array and assign values to variables in their respective locations. As long as the pattern on both sides of the equal sign is the same, the variable on the left will be assigned the corresponding value
var arr = [1.2.3]
var [a,b,c] = arr
console.log(a) / / 1
console.log(b) / / 2
console.log(c) / / 3
Copy the code
The default value
Destruct assignment allows you to specify default values.
/ / a
var [a,b,c=999] = [1.2]
console.log(a) / / 1
console.log(b) / / 2
console.log(c) / / 999
/ / two cases
var [a,b,c=55,d=66,e] = [1.2.null.undefined]
console.log(a) / / 1
console.log(b) / / 2
console.log(c) //null
console.log(d) / / 66
console.log(e) //undefined
Copy the code
Note: ES6 internally uses the strict equality operator (===) to determine whether a position has a value. Therefore, if an array member is not strictly equal to undefined, the default value will not take effect. In the above code, null is not strictly equal to undefined so the default value will not take effect.
The default value can refer to other variables, but the referenced variable must already be declared. Example 4: The error is reported because the y variable has not been declared when x refers to y
/ / a
let [x = 1, y = x] = [];
console.log(x,y) // x = 1,y = 1
/ / two cases
let [x = 1, y = x] = [2];
console.log(x,y) // x=2; y=2
/ / 3
let [x = 1, y = x] = [1.2];
console.log(x,y) // x=1; y=2
/ / 4
let [x = y, y = 1] = [];
console.log(x,y) // ReferenceError:y is not defined
Copy the code
Attention to detail
1. The value of the variable is equal to undefined if deconstruction fails
/ / a
var [a,b,c] = [1.2]
console.log(a) / / 1
console.log(b) / / 2
console.log(c) //undefined
/ / two cases
var [a] = [];
console.log(a) //undefined
Copy the code
2. The right side of the equal sign is not an array, and an error will be reported
/ / a
var [a] = 1;
console.log(a) //TypeError: 1 is not iterable
/ / two cases
let [b] = {};
console.log(b) //TypeError: {} is not iterable
Copy the code
Set assignment can also be used with array assignment
let [x,y,z] = new Set(["a"."b"."c"]);
console.log(x,y,z) //a,b,c
Copy the code
4. Nested parsing assignments
/ / a
var [a,b,c] = [1.2[3]]
console.log(a) / / 1
console.log(b) / / 2
console.log(c) / / [3]
/ / two cases
var [a,b,[c]] = [1.2[3]]
console.log(a) / / 1
console.log(b) / / 2
console.log(c) / / 3
Copy the code
2.2 Object deconstruction assignment
1. Differences with array parsing assignment
The elements of an array are arranged in order, and the value of a variable is determined by its position. However, the properties of an object are not set in order. The variable name must have the same name as the property to obtain the correct value
/ / a
var { name, age } = { age: Awesome!.name: "bbb" };
console.log(name) //bbb
console.log(age) / / 666
/ / two cases
var { name, age ,sex } = { age: Awesome!.name: "bbb" };
console.log(name) //bbb
console.log(age) / / 666
console.log(sex) //undefined
Copy the code
In the first example above, the order of the attributes with the same name on the left and right sides of the equal sign is different, but it does not affect the value. In the second example, the sex variable has no corresponding attribute name, so it cannot get the value, and finally equals undefined.
Attention to detail
1. Object deconstruction assignment is short for the following form. The internal mechanism of object deconstruction assignment is to first find the property of the same name and then assign it to the corresponding variable. It is the latter, not the former, that is really assigned
var {name:n, age:a } = { age: Awesome!.name: "bbb" };
console.log(n) //bbb
console.log(a) / / 666
console.log(name) //ReferenceError: name is not defined
console.log(age) //ReferenceError: age is not defined
Copy the code
2. For variables destructed with let and const declarations, variables must not be declared repeatedly, otherwise an error will be reported
/ / a
let age;
let {age} = {age: 1}; // SyntaxError: Duplicate declaration "age"
/ / two cases
let age;
({age} = {age: 1});
console.log(age) / / 1
Copy the code
In example 2, the parentheses on the bottom line of the let command are required or an error will be reported because the parser will interpret the opening brace as a block of code rather than an assignment statement
2. Similarity with array resolution assignment
Like arrays, deconstruction can also be used for nested structured objects.
var { p: [x, {y} ]} = {p: ['hello', {y:"world"}};console.log(x,y) //hello world
Copy the code
Note that p is not a variable, and y is not a variable.
The deconstruction of an object can also specify default values. The default is valid only if the object’s attribute value is strictly equal to undefined.
var {x = 3} = {x: null};
console.log(x) //null
Copy the code
Arrays are special objects in nature, so they can be deconstructed into object properties.
var arr = [1.2.3];
var {0 : first, [arr.length - 1] : last} = arr;
console.log(first) / / 1
console.log(last) / / 3
Copy the code
[arr. Length-1] = 2; [arr. Length-1] = 3
2.3 String deconstruction assignment
Basic usage
The string is converted to an array-like object during structural assignment
var [a,b,c,d,e] = 'hello';
console.log(a) //"h"
console.log(b) //"e"
console.log(c) //"l"
console.log(d) //"l"
console.log(e) //"o"
Copy the code
2.4 Deconstructive assignment of function parameters
Basic usage
1. Function arguments can be destructively assigned
function add([x, y]){
return x + y;
}
console.log(add([1.2])); / / 3
Copy the code
2. Function arguments can also be destructed using default values.
function add([x = 5, y]){
return x + y;
}
console.log(add([, 2])); / / 7
Copy the code
2.5 Purpose of variable analytical assignment
1. Swap variable values
[x,y] = [y,x]
Copy the code
2. Return multiple values from a function
Normally a function can only return one value. If you want to return more than one value, you have to put the returned data into an array or object, but in ES6 you can use destruct assignment to retrieve the returned data
// Return an array
function f(){
var arr = [1.2.3.4]
return arr;
}
var [a,b,c,d] = f()
console.log(a); / / 1
console.log(b); / / 2
console.log(c); / / 3
console.log(d); / / 4
// Return an object
function obj(){
var obj = {
name:"zhangsan".age:23.sex:"man"
}
return obj;
}
var {name,age,sex} = obj()
console.log(name); //zhangsan
console.log(age);/ / 23
console.log(sex);//man
Copy the code
3. Definition of function parameters Destructuring assignment makes it easy to map a set of parameters to variable names
/ / a
// The parameter structure is an array, so the parameters are assigned in order
function f([x,y,z]){
console.log(x,z,y) //x = 1, z = 3, y = 2
}
f([1.2.3])
/ / two cases
// The structure of the parameters is the form of an object, and the parameters are assigned to the same attribute name
function f({x,y,z}){
console.log(x,y,z) //x =2,y = 3,z = 1
}
f({z:1.x:2.y:3})
Copy the code
Deconstructing assignment is especially useful for extracting data from JSON objects
var jsonData = {
id: 42.status: "NO".data: [88.66]};let { id, status, data: number } = jsonData;
console.log(id, status, number) // 42 'NO' [ 88, 66 ]
Copy the code
5. Traverse the Map structure
/ / a
var map = new Map(a); map.set('first'.'hello');
map.set('second'.'world');
for (let i of map) {
console.log(i); //[ 'first', 'hello' ] [ 'second', 'world' ]
}
/ / two cases
var map = new Map(a); map.set('first'.'hello');
map.set('second'.'world');
for (let [key,value] of map) {
console.log(key + ":" + value); //first:hello second:world
}
Copy the code
3. ES6 string extension
3.1 Template Strings
Basic usage
In traditional JS language, output template is more troublesome, strings and variables need to use the + concatenation, splicing together, ES6 added a new template string, to solve the problem of traditional writing cumbersome
1. Template strings are identified by backquotes (‘) and can be used as regular strings, to define multi-line strings, or to embed variables in strings
// Embed variables in strings
var name = "Tom",time = "today";
console.log(`Hello ${name}, how are you ${time}? `) //Hello Tom, how are you today?
Copy the code
2. If you need to use backquotes in a template string, use a backslash to escape it.
// Embed variables in strings
var str = `\`Hello\` Wrode`
console.log(str) // `Hello` Wrode
Copy the code
3. If a template string is used to represent a multi-line string, all whitespace and indentation are preserved in the output. If you don’t want this newline, you can use ittrimMethod to eliminate it.
console.log(
`
`
)
/*
*/
Copy the code
4. Insert variable in the template string, write variable name in ${}. You can put any JavaScript expression inside curly braces, perform operations, reference object properties, and call functions.
function fn() {
return "World";
}
console.log(`Hello ${fn()}! `) //Hello World!
Copy the code
5. Because JavaScript code is executed inside the braces of the template string, if there is a string inside the braces, it will be printed as is. Template strings can also be nested
// Output as is
console.log(`Hello "World"`) //Hello "World"
// Template string nesting
const tmpl = addrs= > `
<table>
${addrs.map(addr => `
<tr><td>${addr.first}</td></tr>
<tr><td>${addr.last}</td></tr>
`).join(' ')}
</table>
`;
const data = [
{ first: '<Jane>'.last: 'Bond' },
{ first: 'Lars'.last: '<Croft>'},];console.log(tmpl(data));
// <table>
//
//
// Bond
//
// Lars
//
//
// </table>
Copy the code
3.2 the trim ()
Remove string whitespace. In general, regular expressions are used more
-
Trim left and right Spaces are removed
-
TrimLeft left space removed
-
TrimRight right space removed
var str = " a b c "
console.log(str.trim()) //"a b c"
Copy the code
3.3 repeat ()
Meaning and Usage
Repeat () returns a new string, indicating that the original string will be repeated n times
var str = "A"
str.repeat(3)
console.log(str.repeat(3)) //AAA
Copy the code
Pay attention to
1. Repeat () has no effect on the original string.
2. If the repeat()d parameter is rounded downward, an error is reported if it is negative
3. The NaN parameter is equivalent to 0
3.4 Includes () startsWidth() and endsWith()
Meaning and Usage
Three new methods have been added in ES6 to determine whether a string is contained within another string
-
Includes (): indicates whether the parameter string was found, returning a Boolean value
-
StartsWidth (): indicates whether the parameter string is at the head of the source string, returning a Boolean value
-
EndsWith (): Indicates whether the argument string is at the end of the source string, returning a Boolean value
var s = 'Hello world! ';
s.startsWith('Hello') // true
s.endsWith('! ') // true
s.includes('o') // true
Copy the code
Note: All three methods support the second argument. With the second argument n, endsWith() is for strings before n and includes() and startsWidth() is for strings after n to the end.
var s = 'Hello world! ';
s.startsWith('world'.6) // true
s.endsWith('Hello'.5) // true
s.includes('Hello'.6) // false
Copy the code
3.5 padStart () and padEnd ()
Meaning and Usage
ES7 introduced the string completion length function, if a string length is not specified, the header or tail will be completed. PadStart and padEnd take two arguments, the first to specify the minimum length of the string, and the second to complete the string
- PadStart () is used for head completion
- PadEnd () is used for tail completion
'x'.padStart(5.'ab') // 'ababx'
'x'.padStart(4.'ab') // 'abax'
Copy the code
Pay attention to
1. If the length of the original string is equal to or greater than the specified minimum length, the original string is returned
console.log("bbb".padStart(2."ac")) //bbb
Copy the code
2. If the sum of the length of the string used for completion and the original string exceeds the specified minimum length, the string that exceeds the number of bits is truncated.
'x'.padStart(4.'abc') // 'abax'
Copy the code
3. If the second parameter is omitted, a space is used to complete the length.
Common use
1. Specify bits for numeric completion
2. Prompt string format
// Complete the specified number of digits
'1'.padStart(10.'0') / / "0000000001"
// Prompt string format
'09-12'.padStart(10.'YYYY-MM-DD') // "YYYY-09-12"
Copy the code
ES6 array extension
4.1 Array. The from ()
Meaning and Function
Meaning This method is a static method of the Array constructor
The array-like function converts array-like objects and traversable objects (including ES6’s new data structures Set and Map) into true arrays
Common array-like objects
- The NodeList collection returned by DOM operations (example 1)
- Arguments objects inside functions (as in Example 2)
<! - case - >
<body>
<p>1</p>
<p>2</p>
<p>3</p>
</body>
<script>
let ps = document.querySelectorAll('p');
Array.from(ps).forEach(function (p) {
console.log(p);
});
//<p>1</p>
//<p>2</p>
//<p>3</p>
</script>
Copy the code
/ / two cases
function f(){
var args = Array.from(arguments)
console.log(args) / /,8,6,7 [1]
}
f(1.8.6.7)
Copy the code
Array.from can also take a second argument, similar to the map method of arrays, that is used to process each element and place the value in the returned Array.
Array.from([1.2.3], (x) => x * x) / / [1 minus 2]
Copy the code
Common Usage Examples
1. Extract the text content of a set of DOM nodes
<body>
<span class="dd">hh</span>
<span class="dd">xx</span>
<span class="dd">ll</span>
</body>
<script>
let spans = document.getElementsByTagName('span');
//Array.from()
let name1 = Array.from(spans,s=>console.log(s.textContent)) // hh dd ll
// map()
let name2 = Array.prototype.map.call(apans,s=>console.log(s.textContent))
</script>
Copy the code
2. Return various data types
function typrOf(){
return Array.from(argurments,values=>typeof value)
}
typeOf(null[],NaN) //['object', 'object', 'number']
Copy the code
4.2 Array) of ()
Meaning and Purpose
The array.of () method is used to convert a set of values to an Array
The purpose is to compensate for the Array constructor Array(), which behaves differently depending on the number of arguments
Pay attention to
-
There is no overloading due to different parameters. It’s very uniform in its behavior.
-
Array.of always returns an Array of parameter values. If there are no arguments, an empty array is returned.
Array.of() / / []
Array.of(undefined) // [undefined]
Array.of(1) / / [1]
Array.of(1.2) / / [1, 2]
Copy the code
4.3 Find () and findIndex() of Array Instances
Differences between find() and findexIndex()
1. Find () is used to find the first member of an array that meets the criteria, and returns undefined if none of the elements meets the criteria.
FindIndex () returns the location of the first qualified array member, or -1 if all members fail.
[1.5.10.15].find(function(value, index, arr) {
return value > 9;
}) / / 10
[1.5.10.15].findIndex(function(value, index, arr) {
return value > 9;
}) / / 2
Copy the code
Similarities between find() and indexIndex()
1. The arguments to find() and findIndex() are both callback functions, which can take three arguments: the current value, the current position, and the original array
2. Both methods can take a second argument that binds the this object of the callback function.
3. Both methods can find nans, compensating for the IndexOf methods in arrays.
[NaN].indexOf(NaN)
// -1
[NaN].findIndex(y= > Object.is(NaN, y))}) / / 0
Copy the code
4.4 Array Instance Fill ()
meaning
Meaning The fill method fills an array with a given value. Parameter Meaning Fill can take the second and third parameters, which specify the start and end positions of the fill but not the end position
new Array(3).fill(7)
/ / (7, 7, 7)
['a'.'b'.'c'].fill(6.1.2) // Indicates that the start position is 1 of the array index and the end position is 2 of the array index, excluding the end position
// ['a', 6, 'c']
Copy the code
4.5 Array instance entries(),key(),values()
meaning
Both are used to iterate over groups of numbers. They both return an traverser object, which can be used for… The of loop iterates.
The difference between
-
Keys () is a traversal of key names
-
Values () is a traversal of key values
-
Entries () is a traversal of key-value pairs.
for (let index of ['a'.'b'].keys()) {
console.log(index);
}
/ / 0
/ / 1
for (let elem of ['a'.'b'].values()) {
console.log(elem);
}
// 'a'
// 'b'
for (let [index, elem] of ['a'.'b'].entries()) {
console.log(index, elem);
}
// 0 "a"
// 1 "b"
Copy the code
4.6 Array includes()
meaning
Meaning indicates whether an array contains a given value. This method returns a Boolean value
[1.6.3].includes(3); // true
[1.6.3].includes(4); // false
[1.2.NaN].includes(NaN); // true
Copy the code
Attention to detail
- The second argument to this method represents the starting position of the search, which defaults to 0. If the second argument is negative, it represents the reciprocal position, and if it is greater than the array length (for example, if the second argument is -4, but the array length is 3), it is reset to start at 0.
- It is also common to check for the inclusion of a value using the indexOf method of an array. But it can lead to NaN’s misjudgment
4.7 Extended operators for arrays
role
It is written as three full stops in English namely…
Function to convert data structures into arrays. You’re essentially making a copy of an array.
var arr = [1.2.3]
var arr1 =[...arr]
console.log(arr1) / / [1, 2, 3]
arr[0] = 66;
console.log(arr) / / [66, 2, 3]
console.log(arr1) / / [1, 2, 3]
Copy the code
The extension operator can be used to convert an array of classes into an array
Summary: There are several ways to convert an array of classes into an array:
-
Array.prototype.slice.call();
-
Array.from();
-
[… array like object]
5. ES6 object extensions
5.1 Shorthand for attributes
- In ES6, if the attribute name is equal to the variable replacing the attribute value, the attribute value may not be written as follows
var str = "hello"
var obj1 = {str}
console.log(obj1) //{ str: 'hello' }
Copy the code
- Similarly, a method name can be omitted in an object if it is equal to the variable that defines it.
function say(){
console.log("hello")}var obj = {
say
}
console.log(obj.say()) //hello
Copy the code
It would be much easier to write it this way
5.2 Object.is(a)
In ES5 although there are two operators can compare two values are equal, but has its own advantages and disadvantages, such as (= =) operator will automatically transform the data type, NaN (= = =) operator is not equal to NaN, 0 equals + 0, is there a operator, consider only as long as the two values are equal, they should be equal to the operator, Therefore, in ES6, the “equal value” algorithm, namely object.is (), is proposed to compare whether two values are exactly equal, which is basically the same as the behavior of (===)
Object.is(+0.0) //false
Object.is(NaN.NaN)//true
Object.is({},{})//true
Object.is("str"."str")//true
Copy the code
5.3 the Object. The assign ()
Object.assign is used to merge objects, copying all the enumerable properties of the source Object to the target Object. You can have multiple arguments, but the first argument is the target object and the following arguments are the source object.
var target = {a:1.b:2}
var obj1 = {b:3.c:4}
var obj2 = {b:11.d:55}
var obj = Object.assign(target,obj1,obj2)
console.log(obj) // { a: 1, b: 11, c: 4, d: 55 }
Copy the code
Pay attention to
-
If the target object has an attribute with the same name as the source object, or if multiple source objects have an attribute with the same name, the following attribute overrides the preceding one.
-
The return value of this method is a reference to the first argument, which returns the first argument.
-
This method copies the data on the prototype as well.
-
You cannot copy inherited properties or non-enumerable properties
-
This method is shallow copy.
Common use
- Add attributes to an object
class Point {
constructor(x, y) {
Object.assign(this, {x, y}); }}// Add the x and y attributes to the Object instance of the Point class using the object. assign method.
Copy the code
- Add methods for objects
function Example(){
}
Example.prototype.showTab = function(){
console.log("Hello")}Object.assign(Example.prototype,{
say(){
console.log("world")
},
see(){
console.log("Hi")}})var example = new Example()
console.log(example.showTab()) //Hello
console.log(example.say()) //world
console.log(example.see()) //Hi
Copy the code
- Clone object
- Merging multiple objects
- Specify default values for properties
5.4 Attribute-related methods
1. Obect. GetOwnProertyDescriptor () to obtain detailed information about a property of an object (a)
2. Object.defineproperty () Fine setting a single attribute of an Object (Example 2)
- Specifies whether the video system can be deleted
- Writeable Whether to modify
- Enumerable Whether you can enumerate
- Value: indicates the value of an attribute
3. Object.defineproperties () Fine setting multiple attributes of an Object (Example 3)
4. Property retrieved from getOwnPropertyNames() and returned as an array (Example 4)
5. object.keys () gets the property name of an Object and puts the property name in an array (Example 5)
6. object.values () gets the value of the Object and puts it in an array (Example 6)
/ / a
var obj = {
name:"wangcai".age:16
}
console.log(Object.getOwnPropertyDescriptor(obj,"name"))
/*{ value: 'wangcai', writable: true, enumerable: true, configurable: true } */
/ / two cases
// Add an attribute
Object.defineProperty(obj,"name", {configurable:true.value:"wangcai"})
/ / 3
// Add multiple attributes
Object.defineProperties(obj,
{
name: {configurable:true.value:"wangcai"},
id: {writeable:false.value:"123456"}})/ / 4
var obj = {
name:"wangcai".age:16
}
console.log(Object.getOwnPropertyNames(obj)) //[ 'name', 'age' ]
/ / cases of five
var obj = {
name:"wangcai".age:16
}
console.log(Object.keys(obj)) //[ 'name', 'age' ]
/ / 6
var obj = {
name:"wangcai".age:16
}
console.log(Object.values(obj)) //[ 'wangcai', 16 ]
Copy the code
5.5 Object inheritance related methods
1.object.create () Using object.create is suitable for inheriting literal objects. 2. GetPrototypeOf () gets the Prototype property of the constructor that created this object
/ / a
var newObj = Object.create({}, {
size: {
value: "large".enumerable: true
},
shape: {
value: "round".enumerable: true}});console.log(newObj.size) //large
console.log(newObj.shape) //round
console.log(Object.getPrototypeOf(newObj)) / / {}
/ / two cases
var obj = {
name:"wangcai".age:16
}
console.log(Object.getPrototypeOf(obj)==Object.prototype)
Copy the code
5.6 Object Traversal Summary
There are several ways to traverse an object’s properties in ES6
- For in: outputs enumerable properties for itself and the stereotype chain.
- Keys () : Used to get the enumerable property keys of the Object itself
- Object. GetOwnPropertyNames () : all the property name used to retrieve the Object itself
5.7 Extension operators for objects
The Object extension operator takes all the traversable properties of the parameter Object and assigns them to the current Object. (As you can see here, the Object extension operator is the same as object.assign ().)
let z ={a:6.b:4}
letn = {... z}console.log(n) //{a:6,b:4}
console.log(Object.assign({},z)) //{a:6,b:4}
Copy the code
role
- Can be used to merge two objects
- Note that if a user-defined attribute is placed after an extension operator, the attributes of the same name inside the extension operator will be overwritten.
let a = {x:55.y:66
}
let x = 1, y = 2, aWithOverrides = { ... a, x, y };console.log(aWithOverrides) //{ x: 1, y: 2 }
Copy the code
Due to the length of the remaining knowledge points open another
Stay tuned for function extensions, Class, Set, and Map data structures, Iterator, and for in ES6… of
[References]
Ruan Yifeng ES6 introduction