js解构赋值大全

解构赋值规则:只要等号右边的值不是对象,就先将其转为对象undefinednull无法转为对象,不能使用解构。

数组解构

// 按顺序解构
const arr = [1, 2, 3]
const [a, b, c] = arr
a// 1
b// 2
c// 3

// 数组长度解构
const arr = [1, 2, 2, 3, 4, 5, 0]
const { length } = arr
length// 7

// 默认值解构,能取到值就不取默认值
let [x = 1, y = x] = [2]
x// 2
y// 2

对象解构

// 对象赋值的机制,先找到同名属性,再将值赋值给变量
const obj = {
  name: 'zhangsan',
  age: 20,
  grads: 90
}
const { name: name, age: age } = obj
const { name, age } = obj
name// 'zhangsan'
age// 20

const {name: nameR} = obj
name// undefined
nameR// 'zhangsan'


// 默认值解构---默认值生效的条件是,对象的属性值严格执行等于undefined
const { x = 3, y } = {}
x// 3
y// undefined

const { y = 3 } = { y: undefined}
y// 3

const { x = 3 } = { x: null }
x// null

字符串解构

const str = '123456'
const [a, b, c, d, e, f] = str
const { length } = str
a// 1
b// 2
c// 3
.
.
length// 6

数值和布尔值的解构

// 数值和布尔值都有包装对象`toString`
let { toString: s } = 123
s === Number.prototype.toString // true

let {  toString: s } = true
s === Boolean.prototype.toString// true

函数参数解构

// 参数为数组
function add([x, y]) {
  return x + y
}
add([1, 2])

[[1,3], [2, 4]].map(([a, b]) => a + b)

//参数为对象
function move({x = 0, y = 0} = {}) {
  return [x, y]
}
move({x: 3, y: 5})// [3, 5]
move({x: 3})// [3, 0]
move({})// [0, 0]
move()// [0, 0]

// 下面写法会有错误,实际是有值从传入值取,没值才取默认对象的值。所以当传入对象只有x时,y在传入对象中找不到
function move({x, y} = {x: 0, y: 0}) {
  return [x, y]
}
move({x: 3, y: 5})// [3, 5]
move({x: 3})// [3, undefined]
move({})// [0, undefined]
move()// [0, undefined]

嵌套对象解构

// 嵌套数组字符串
const obj = {
  arr: [
    'hello',
    { y: 'World' }
  ]
}

const {arr: [x, { y }]} = obj
x// 'hello'
y// world

// 嵌套对象
const obj = {
  a: {
    b: {
      name: 'zhangsan'
    }
  }
}
const {a: {b: {name}}} = obj
name: // 'zhangsan'
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值