es6结构赋值

本文详细介绍了JavaScript中的解构赋值语法,包括数组、对象、字符串、函数参数的解构,以及默认值和模式匹配等特性。解构赋值提供了一种简洁且强大的方式来提取和赋值数据,尤其在处理数组和对象时非常有用。同时,它也适用于具有Iterator接口的数据结构。文章还展示了如何在实际场景中利用解构赋值进行变量优化和简化代码。
摘要由CSDN通过智能技术生成

变量赋值优化

//定义多个变量
let [a, b, c] = [1, 2, '3'];
console.log(a) //1
console.log(b) //2
console.log(c) //3
//如果定义变量的数量与赋值的数量不相同,超出的部分将会被忽略,缺少的变量只会被定义单不会被赋值
let [a, b, c] = [1, 2, 3, 4, 5];
console.log(a) //1
console.log(b) //2
console.log(c) //3

let [a, b, c] = [1, 2];
console.log(a) //1
console.log(b) //2
console.log(c) //undefined

//模式匹配
let [foo, [[bar], baz]] = [1, [[2], 3]];
foo // 1
bar // 2
baz // 3

let [ , , third] = ["foo", "bar", "baz"];
third // "baz"

let [x, , y] = [1, 2, 3];
x // 1
y // 3

let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]

let [x, y, ...z] = ['a'];
x // "a"
y // undefined
z // []

//赋值数据不为数组时会报错
let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {};

//只要数据结构具有 Iterator 接口,都可以采用数组形式的解构赋值
//Iterator是为各种不同的数据结构提供统一的访问机制(https://wangdoc.com/es6/iterator.html)
//具备Iterator接口的原生数据:Array、Map、Set、String、TypedArray、、函数的 arguments 对象、NodeList 对象

//解构赋值的默认值
let [ x = 1, y = 2, z = 3 ] = [ undefined, null ] //赋值为空或undefined时,使用设置的默认值
x //1
y //null
z //3

对象的解构赋值

//对象结构赋值根据属性提取,需要确保属性值与变量名相同,对于排序没有要求。
let { a, c, b } = { a: 1, b: 2, c: 3 }
console.log(a) //1
console.log(b) //2
console.log(c) //3
//自定义变量名
let { a: x } = { a: 1 }
console.log(a) //a is not defined
console.log(x) //1
//默认值
let { a = 1, b = 2, c: z = 3 } = { x: 1, y: 2 }
console.log(a) //1
console.log(b) //2
console.log(c) //3

字符串的解构赋值

//字符结构
const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"
//解构length
let {length : len} = 'hello';
len // 5

函数参数的解构赋值

function add([x, y]){
  return x + y;
}

add([1, 2]); // 3

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值