javascript - const [a, b, c] = array 有什么区别?和 const {a, b, c} = 数组;
问题描述
const [a, b, c] = array;
const {a, b, c} = array;
问:这两种说法有什么区别?
解决方案
第一个是可迭代解构。a
将获得 中的第一个值array
,b
将获得第二个值,并将c
获得第三个值。
二是对象解构。a
将获得 的值array.a
,b
将获得 的值array.b
,c
并将获得 的值array.c
。(通常不是您想要的数组。)
第一个例子:
const [a, b, c] = ["ay", "bee", "see"];
console.log(a, b, c);
该示例使用数组,但源可以是任何可迭代对象。
第二个示例(对象解构),带有一个数组:
const array = ["ay", "bee", "see"];
const {a, b, c} = array;
console.log(a, b, c);
当然,在正常情况下,这些都是undefined
(如上所示),因为数组通常不具有这些属性。
第二个示例(对象解构),具有非数组对象:
const obj = {a: "ayy", b: "bee", c: "see"};
const {a, b, c} = obj;
console.log(a, b, c);
尽管可以,但通常不会对数组使用对象解构,因为数组是对象。当您想从数组中挑选特定条目时,它很有用,例如这段代码挑选索引 2 和 4 处的值:
const array = ["ay", "bee", "see", "dee", "eee"];
const {2: c, 4: e} = array;
console.log(c, e); // "see" "eee"
您甚至可以使用解构模式中的计算属性表示法对来自变量的索引执行此操作:
const array = ["ay", "bee", "see", "dee", "eee"];
const indexA = Math.floor(Math.random() * array.length);
const indexB = Math.floor(Math.random() * array.length);
const {[indexA]: a, [indexB]: b} = array;
console.log(`${indexA}: ${a}, ${indexB}: ${b}`); // Varies depending on the random indexes
更多关于 MDN的信息。
推荐阅读
- wordpress - Wordpress ...如果删除了外部帖子,则删除帖子
- java - Google Speech to Text“不可用:凭据无法获取元数据”
- xslt - 如何在对组求和之前将 current_group() 中的每个值设置为其绝对值?
- mamp - Mamp不会启动apache windows 10
- javascript - 找到两个数组之间的对称差异
- python - 如何将具有相似类型技能的集群组合在一起?
- c++ - CMake没有定义变量
- docker - 使用预定义的 Redis 转储创建 Docker 容器
- python - jinja 有没有办法在异常之前输出其部分渲染的内容?
- java - 如何撤消在java中移动到垃圾箱的操作?