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'

猜你喜欢

转载自blog.csdn.net/tshjy1/article/details/106196522