简体   繁体   English

解构数组

[英]Destructuring Array

b is undefined and when assigned 'a' as default values it gets it but when assigned 'c' value it gives throw an Error can someone explain better what's happening here or is this a bug? b 是未定义的,当分配 'a' 作为默认值时,它会得到它,但是当分配 'c' 值时,它会抛出一个错误,有人可以更好地解释这里发生了什么,还是这是一个错误?

const [a, b = c, c] = [1, , 3]

Destructuring into variables evaluates left-to-right in the order of the array (or property list).解构为变量会按照数组(或属性列表)的顺序从左到右进行计算。

Variables declared with const cannot be accessed before the line that initializes them runs.在初始化它们的行运行之前,不能访问用const声明的变量。

Your code is equivalent to:您的代码相当于:

const arr = [1, , 3];
const a = arr[0];
const b = arr[1] === undefined ? arr[1] : c;
const c = arr[2];

Which should make the problem pretty obvious;这应该使问题非常明显; you're trying to retrieve c before the interpreter has gotten to that point.您正在尝试在解释器到达该点之前检索c It's not a bug.这不是一个错误。

For the output you're looking for, extract c first, so you can use it as a default value for b .对于您要查找的 output,请先提取c ,以便将其用作b的默认值。

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

But I'd also recommend avoiding sparse arrays when possible, they can be pretty unintuitive.但我也建议尽可能避免使用稀疏的 arrays,它们可能非常不直观。

It is possible to do this in one line.可以在一行中执行此操作。 You can destructure the keys of the array.您可以解构数组的键。 Get the 2nd index before 1st and set that as the default value.在第一个索引之前获取第二个索引并将其设置为默认值。 This is purely academic and don't use it in actual code base.这纯粹是学术性的,请勿在实际代码库中使用它。

 const { 0: a, 2: c, 1: b = c } = [1, , 3] console.log(a, b, c)

const [a, b = c, c] = [1, , 3]

The statement above could be thought of as上面的陈述可以被认为是

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

Whereas, the statement below鉴于,下面的声明

const [a, b = c, c] = [1, , 3]

Could be thought of as可以认为是

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

So, in the first case c is being referred before is it initialized which gives an error but in the second case a is already present when it is being referred.因此,在第一种情况下, c之前被引用过,它是否已初始化,这会产生错误,但在第二种情况下a在被引用时已经存在。

Now, if you try the same thing using var , then you wouldn't be getting an error in the first case because of hoisting .现在,如果您使用var尝试相同的操作,那么在第一种情况下您不会因为提升而收到错误。

var [a, b = c, c] = [1, , 3]
console.log(a, b, c) //1 undefined 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM