小编的上一篇文章更新了 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 3
let [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] 5
let [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.name
let age = user.age
console.log(name,age) // lilei 34
2、es6 语法
let user = {
name:"lilei",
age:34
}
let {name,age} = user
console.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} = user
console.log(name,age) // lilei 34
5、变量重命名
let user = {
name:"lilei",
age:34
}
let {name:uname,age:uage} = user
console.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 3
function 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