ES6 嵌套数组解构软失败

ES6 nested array destructuring soft fail

如何管理ES6嵌套数组的软失败?

假设我们有一个包含项目的嵌套数组,我们想要获取第一个项目:

const array = [[3,4,5,6]];
const [[firstItem]] = array; // firstItem = 3

console.log(firstItem);

我想防止数组带有 null 的情况,但显然它的工作方式与处理对象软失败不同:

const array = [null];
const [[firstItem] = []] = array; // Uncaught TypeError: array is not iterable

console.log(firstItem);

以下是您可以确定的方法,默认情况下 firstItem 始终是一个空数组(传递 null 值的情况除外):

const array = [];
const [[firstItem = []] = [] ] = array;

console.log(firstItem)

const array = [[1]];
const [[firstItem = []] = [] ] = array;

console.log(firstItem)

来自destructuring assignment

Default values

A variable can be assigned a default, in the case that the value unpacked from the array is undefined.

您的值是 null 而不是 undefined

const array = [undefined];
const [[firstItem] = []] = array; // Uncaught TypeError: array is not iterable

console.log(firstItem);