解构赋值
按照一定的模式,从数组或对象中把数据拿出来,对变量进行赋值
一、数组解构赋值
等号左边与右边必须都是数组,数组的解构赋值要一一对应,对应不上就是undefined
let [a,b,c] = [1,2,3]
console.log(a,b,c) //1,2,3
let [h,,i,j] = [1,2,3]
console.log(h,i,j) //1,3,undefined(对应不上)
//可以用来获取函数的返回值
function fn(){
return ["red","green","blue"]
}
let [rr,gg,bb] = fn()
console.log(rr,gg,bb) //"red","green","blue"
二、对象解构赋值
等号左边与右边必须都是对象,名字要一一对应,顺序不需要对应,对应不上的值的结果是undefined
let obj = {
id:1,
name:"张三",
age:18,
language:["html","css","js"],
study:function(){
console.log("学习方法")
}
}
let {id,name,age,language,study} = obj
console.log(id,name,age,language,study)
注意:如果变量之前已经被声明了,再次赋值的时候不能加
let
并且整个赋值语句要用小括号包裹起来,以防止程序识别成作用域
({id,name,age,language,study} = obj)
网友评论