小编的上一篇文章更新了es6中对于变量定义的问题,这篇文章持续来一些实用的干货,对于数组、对象的赋值问题。特地是在前后端合作项目的时候,对后端数据的拆分,还有就是对于函数的默认值的惰性赋值问题。看完上面的,置信会忍不住对es6伸出大拇指。真是太不便了。大家也能够关注我的微信公众号,蜗牛全栈。
一、数组的构造赋值
1、es5语法
let arr = [1,2,3]let a = arr[0]let b = arr[1]let c = arr[2]console.log(a,b,c) // 1 2 3
2、es6语法
let [a,b,c] = [1,2,3]console.log(a,b,c) // 1 2 3let [a,b,c] = [1,2,[3,4]]console.log(a,b,c) // 1 2 [3,4] let [a,b,c,d] = [1,2,[3,4]]console.log(a,b,c) // 1 2 [3,4] undefind
3、惰性赋值
let [a,b,c,d = 5] = [1,2,[3,4]]console.log(a,b,c) // 1 2 [3,4] 5let [a,b,c,d = 5] = [1,2,[3,4],6]console.log(a,b,c) // 1 2 [3,4] 6
二、对象的构造赋值
1、es5语法
let user = { name:"lilei", age:34}let name = user.namelet age = user.ageconsole.log(name,age) // lilei 34
2、es6语法
let user = { name:"lilei", age:34}let {name,age} = userconsole.log(name,age) // lilei 34
3、惰性赋值(默认值)
let {name,age=18} = { name:"lilei"}console.log(name,age) // lilei 18
4、对象解构赋值的时候,与程序无关,只与key无关
let user = { name:"lilei", age:34}let {age,name} = userconsole.log(name,age) // lilei 34
5、变量重命名
let user = { name:"lilei", age:34}let {name:uname,age:uage} = userconsole.log(name,age) // 报错,console.log(uname,uage) // lilei 34
三、字符串解构赋值
1、es5语法
let str = "abcde"for(let i = 0;i<str.length;i++){ console.log(i) // a b c d e}
2、es6语法(类比数组解构赋值)
let [a,b,c,d,e] = "abcde"console.log(a,b,c,d,e) // a b c d e
四、json解构赋值
let json = '{"a":"hello","b":"world"}'let {a,b} = JSON.parse(json) console.log(a,b) // hello world
五、对于惰性赋值实例
1、函数参数
function foo([a,b,c]){ console.log(a,b,c)}let arr = [1,2,3]foo(arr) // 1 2 3function foo({name,age}){ console.log(name,age)}let obj = { name:"lilei", age:18}foo(obj)
2、函数返回值
function foo(){ let obj = { name:"lilei", age:18, school:"University" } return obj}let {name,age} = foo()console.log(name,age) // lilei 18
3、函数参数默认值
function foo({name,age,school="University"}){ console.log(name,age,school)}let obj = { name:"lilei", age:18}foo(obj) // lilei 18 University
4、其余
function foo(){ console.log(123)}let [a=foo()] = [1] // 什么也不输入let [a=foo()] = [] // 输入123