Assignmentdestructuringandoperatorprecedence
创始人
2024-09-20 18:00:17
0

Assignment destructuring是ES6引入的一种新特性,它允许我们通过一种语法形式从数组或对象中提取值并将其赋值给变量。

假设我们有一个数组,我们想将其第一项和第二项分别赋值给变量a和b:

const arr = [1, 2, 3, 4, 5];
const [a, b] = arr;
console.log(a); // 1
console.log(b); // 2

我们还可以使用默认值来避免undefined情况:

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

同时,我们可以在函数参数中使用assignment destructuring:

function foo({ a, b }) {
  console.log(a, b);
}
foo({ a: 1, b: 2 }); // 1 2

在使用assignment destructuring时,需要注意运算符优先级。例如:

const obj = { a: 1, b: 2 };
const a = obj.a || 0; // 1
const b = obj.b || 0; // 0

这里的问题在于 || 运算符的优先级比 = 运算符的优先级高,所以变量a不会被赋值为0。解决方法是给整个表达式加上括号:

const obj = { a: 1, b: 2 };
const a = (obj.a || 0); // 1
const b = (obj.b || 0); // 2

相关内容

热门资讯

新手必备!wepoker有辅助... 新手必备!wepoker有辅助器吗,wpk有作弊吗,一直是有挂(有挂技术)1、每一步都需要思考,不同...
玩家必看教程!pokemmo脚... 玩家必看教程!pokemmo脚本辅助器,hh poker辅助器先试用,果然真的有挂(有挂方针)1、点...
一起来探讨!wepokerpl... 一起来探讨!wepokerplus开挂,德普之星怎么设置埋牌,其实是有挂(有挂助手)一起来探讨!we...
热点推荐!wepoker透视脚... 热点推荐!wepoker透视脚本网页,wepokerplus开挂,确实真的有挂(有挂教程)1、热点推...
玩家必备攻略!wepoker开... 玩家必备攻略!wepoker开脚本视频,hhpoker真能买到挂吗,一直存在有挂(有挂辅助)1、起透...
终于懂了!德扑圈有透视吗,微扑... 终于懂了!德扑圈有透视吗,微扑克数据分析,果然是有挂(有挂教学)1、下载好正确养号方法之后点击打开,...
玩家必备教程!hhpoker德... 玩家必备教程!hhpoker德州作弊,pokermaster脚本,真是存在有挂(证实有挂)运辅助工具...
总算明白!hhpoker德州透... 总算明白!hhpoker德州透视,pokermaster辅助器,总是是有挂(有挂透明挂)一、游戏安装...
一起来探讨!来玩德州破解器,w... 一起来探讨!来玩德州破解器,wepoker作弊视频,都是有挂(有挂秘笈)所有人都在同一条线上,像星星...
实测教程!sohoopoker... 实测教程!sohoopoker辅助,pokemmo脚本,本来是有挂(新版有挂)1、模拟器是什么优化,...