Home > Article > Web Front-end > Detailed explanation of assignment based on ES6 scope and destructuring
This article brings you a detailed explanation of scope and destructuring assignment based on ES6. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
ES6 Force strict mode to be enabled
Scope
•var declares local variables. Variables defined in for/if curly braces can also be accessed outside the curly braces
•The variable declared by let is block scope, and the variable cannot be defined repeatedly
•const declares a constant, block scope, must be assigned a value when declaring, and cannot be modified
// const声明的k指向一个对象,k本身不可变,但对象可变 function test() { const k={ a:1 } k.b=3; console.log(k); }
test() deconstruction Assignment
{ let a, b, 3, rest; [a, b, c=3]=[1, 2]; console.log(a, b); } //output: 1 2 3 { let a, b, 3, rest; [a, b, c]=[1, 2]; console.log(a, b); } //output: 1 2 undefined { let a, b, rest; [a, b, ...rest] = [1, 2, 3, 4, 5, 6]; console.log(a, b, rest); } //output:1 2 [3, 4, 5, 6] { let a, b; ({a, b} = {a:1, b:2}) console.log(a ,b); } //output: 1 2
Usage scenarios
Variable exchange
{ let a = 1; let b = 2; [a, b] = [b, a]; console.log(a, b); }
Get multiple function values
{ function f(){ return [1, 2] } let a, b; [a, b] = f(); console.log(a, b); }
Get multiple function return values
{ function f(){ return [1, 2, 3, 4, 5] } let a, b, c; [a,,,b] = f(); console.log(a, b); } //output: 1 4 { function f(){ return [1, 2, 3, 4, 5] } let a, b, c; [a, ...b] = f(); console.log(a, b); } //output: 1 [2, 3, 4, 5]
Object destructuring and assignment
{ let o={p:42, q:true}; let {p, q, c=5} = o; console.log(p ,q); } //output: 42 true 5
Get json value
{ let metaData={ title: 'abc', test: [{ title: 'test', desc: 'description' }] } let {title:esTitle, test:[{title:cnTitle}]} = metaData; console.log(esTitle, cnTitle); } //Output: abc test
Related recommendations:
Detailed examples of new array methods in ES6
Detailed example of the application of es6 in react
Detailed explanation of the function binding and class event binding functions of javascript in ES6
The above is the detailed content of Detailed explanation of assignment based on ES6 scope and destructuring. For more information, please follow other related articles on the PHP Chinese website!