解构赋值
什么是解构赋值?
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,暂无数据
应用一:
<div class="form">
<input type="text" placeholder="请输入用户名" value="lili"/>
<input type="text" placeholder="请输入密码" value="123"/>
</div>
let [username,pwd] = document.querySelectorAll('input');
console.log(username.value,pwd.value)
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
//1-2 获取年 月
funtion getDate(){
let date = new Date();
let y = date.getFullYear();
let m = date.getMonth() + 1;
return {y,m} //{y:y,m:m}的缩写 缩写的情况:属性名为变量名,属性值为变量的值
}
let {y:year,m:month} = getDate();
//2.函数传参
function sum({x,y=20}){
console.log(x,y); //1,20
}
sum({x:1})
//2.函数的传参解构
function ajax({url,method='get'}){
}
ajax({url:'/api/list'}) // method会使用默认值'get'
ajax({url:'/api/login',method:'post'}) //method的默认值会被传入的post值覆盖掉
//3.根据对象动态创建节点
<div style="font-size:12px" class="wrap"><p></p></div>
let obj = {
tagName:'div',
props:{
tyle:'font-size:12px',
class:'wrap'
},
children:{
tagName:'p',
children:'hello world'
}
};
function createElement(obj){
let {tagName,props,children} = obj;
let el = document.createElement(el);
document.body.appendChild(el);
if(props){
for(let i in props){
el.setAttribute(i,props[i])
}
}
if(typeof children === 'object'){
el.appendChild(createElement(children));
}else{
el.innerHTML = children;
}
return el;
}
createElement(obj)
字符串的解构:
let [a,b,c] = '123';
console.log(a,b,c); //1,2,3
导入模块解构:
import {a,b,c} from './model';
特殊情况
let [a,b] = {name:'lili'} //报错
let {name} = [1,2]; //不会报错 name的值为undefined