解构赋值:解构赋值就是一种模式的匹配,只要等号两边的模式完全相同的,那么左边的变量就会被赋值对应右边的值
PS:数组解构赋值时,是通过索引的唯一性赋值的
let arr = [1,2,3]
let a = arr[0];
let b = arr[1];
let c = arr[2];
console.log(a, b, c)
let [a,b,c] = [1,2,3]
console.log(a,b,c)
// 1 2 3
let [a,b, [d,f]] = [1,2, [3,4]]
console.log(a,b,d,f)
// 1 2 3 4
let [a, b, [d]] = [1,2,[3,4]]
console.log(a, b, d)
// 1 2 3
let [a, b, d] = [1,2,[3,4]]
console.log(a, b, d)
// 1 2 [3,4]
let [a,b,d, e] = [1, 2, [3, 4]]
console.log(a, b, d, e)
// 1 2 [3, 4] undefined
let [a,b,d, e = 5] = [1, 2, [3, 4]]
console.log(a, b, d, e)
// 1 2 [3, 4] 5
let [a,b,d, e = 5] = [1, 2, [3, 4], 6]
console.log(a, b, d, e)
// 1 2 [3, 4] 6
let user = {
name: 'xiaoxiao',
age: 30
}
let name = user.name
let age = user.age
console.log(name, age)
// xiaoxiao 30
let user = {
name: 'xiaoxiao',
age: 30
}
let {name, age} = user
console.log(name, age)
// xiaoxiao 30
let user = {
name: 'xiaoxiao',
age: 30
}
let {age, name} = user
console.log(name, age)
// xiaoxiao 30
let user = {
name: 'xiaoxiao',
age: 30
}
let {age: uage, name: uname} = user
console.log(uage, uname)
// xiaoxiao 30
console.log(age, name)
// Uncaught ReferenceError: age is not defined
// 原有属性名称访问不到, 未定义
let str = 'imooc'
for (let i = 0; i < str.length; i++) {
console.log(str[i]);
}
// i m o o c
let str = 'imooc'
let [a,b,c,d, e] = str
console.log(a,b,c,d, e)
// i m o o c
let [a, b, c =8] = [4,5]
console.log(a,b,c)
// 4 5 8
let {name, age =18} = {name: 'xiaoxiao'}
console.log(name, age)
// xiaoxiao 18
function foo () {
console.log(123)
}
let [a = foo()] = []
console.log(a)
// 1
右侧没有值时,左侧默认值才会执行
function foo () {
console.log(123)
}
let [a = foo()] = []
console.log(a)
// 123
function foo ([a,b,c]) {
console.log(a,b,c)
}
foo([1,2,3])
// 1 2 3
function foo ({name,age,school ='imooc'}) {
console.log(name, age, school)
}
let obj ={
name: 'xiecheng',
age: 34
}
foo(obj)
// xiecheng 34 imooc
function foo () {
let obj = {
name: 'xiecheng',
age: 34,
school: 'xxx'
}
return obj
}
let {name, age} = foo()
console.log(name, age)
// xiecheng 34
// json
let json = '{"name": "xiaoxiao", "sex": "男"}'
// 把json字符串转换为json对象
let {name, sex} = JSON.parse(json)
console.log(name, sex)
// xiaoxiao 男