解構(gòu)賦值
什么是解構(gòu)賦值?
es6允許按照一定的模式,從數(shù)組或?qū)ο笾刑崛≈?,給變量進(jìn)行賦值,稱為解構(gòu)賦值。
特點:
1>給變量賦值
2>值的來源是對象或數(shù)組
3>規(guī)則:按一定的模式
一般用在數(shù)據(jù)交互,ajax請求數(shù)據(jù)。
- 數(shù)組解構(gòu)
//1.這種比較散
let a = 10;
let b = 12;
let c = 13;
console.log(a,b,c); //10,12,13
//2.定義到數(shù)組內(nèi)
let arr = [1,2,3];
console.log(arr[0],arr[1],arr[2]) //1,2,3
//3.解構(gòu)賦值
let [a,b,c] = [1,2,3]
console.log(a,b,c) //1,2,3
//4.解構(gòu)賦值必須兩邊格式一致
let [a,b,c] = [1,[2,3]];
console.log(a,b,c) //1,[2,3],undefined
let [a,[b,c]] = [1,[2,3]];
console.log(a,b,c) //1,2,3
//5.交互數(shù)據(jù)
let a = 10;
let b = 20;
[a,b] = [b,a];
console.log(a,b); //20,10
//給默認(rèn)值
let [a,b,c='暫無數(shù)據(jù)'] = ['aa','bb'];
console.log(a,b,c); //aa,bb,暫無數(shù)據(jù)
- json解構(gòu)
var json = {
'name':'lixd',
'age':'20',
'job':'teacher'
}
let {name,age,job} = json;
console.log(name,age,job); //lixd,20,teacher
//起別名:
let {name,age.job:b} = job;
console.log(name,age,job) //lixd,20,undefined
console.log(name,age,b) //lixd,20,teacher
//給默認(rèn)值
let {name:n,age:a,job:b='teacher'} = {'name':'lixd','age':'20'};
console.log(n,a,b)//lixd,20,teacher
- 函數(shù)解構(gòu)的應(yīng)用
//1.函數(shù)返回數(shù)據(jù),在外側(cè)解構(gòu)
function getPos(){
//......
return {
x:10,
y:20
}
}
let {x,y} = getPos(); //10,20
//2.函數(shù)傳參
function sum({x,y=20}){
console.log(x,y); //1,20
}
sum({x:1})
- 導(dǎo)入模塊解構(gòu)
import {a,b,c} from './model';