解构赋值
什么是解构赋值?
es6允许按照一定的模式,从数组或对象中提取值,给变量进行赋值,称为解构赋值。
特点:
1>给变量赋值
2>值的来源是对象或数组
3>规则:按一定的模式
一般用在数据交互,ajax请求数据。
- 数组解构
//1.这种比较散
let a = 10;
let b = 12;
let c = 13;
console.log(a,b,c); //10,12,13
//2.定义到数组内
let arr = [1,2,3];
console.log(arr[0],arr[1],arr[2]) //1,2,3
//3.解构赋值
let [a,b,c] = [1,2,3]
console.log(a,b,c) //1,2,3
//4.解构赋值必须两边格式一致
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.交互数据
let a = 10;
let b = 20;
[a,b] = [b,a];
console.log(a,b); //20,10
//给默认值
let [a,b,c='暂无数据'] = ['aa','bb'];
console.log(a,b,c); //aa,bb,暂无数据
- json解构
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
//给默认值
let {name:n,age:a,job:b='teacher'} = {'name':'lixd','age':'20'};
console.log(n,a,b)//lixd,20,teacher
- 函数解构的应用
//1.函数返回数据,在外侧解构
function getPos(){
//......
return {
x:10,
y:20
}
}
let {x,y} = getPos(); //10,20
//2.函数传参
function sum({x,y=20}){
console.log(x,y); //1,20
}
sum({x:1})
- 导入模块解构
import {a,b,c} from './model';