如何解构这个数组

How to destructure this Array

如果 widthheight 之前已经声明过,我该如何解构它们?

function test() {
  let height
  let width

  const viewBox = '0 0 24 24'
  const sizeArr = viewBox.split(' ')

  // ESLint is telling me to destructure these and I don't know how
  width = sizeArr[2]
  height = sizeArr[3]
}

您可以使用逗号来忽略不需要的数组中的某些元素:

const [,,width,height] = sizeArr;

function test() {
  const viewBox = '0 0 24 24'
  const sizeArr = viewBox.split(' ')
  const [,,width,height]=sizeArr;
  console.log(width,height);
}
test();

如果出于某种原因需要将 let 声明保留在函数的顶部,您可以从解构中删除 const。请注意,由于自动插入分号,您需要在前一行的末尾添加一个分号。

[,,width,height] = sizeArr;

function test() {
  let height;
  let width;
  const viewBox = '0 0 24 24';
  const sizeArr = viewBox.split(' ');
  [,,width,height]=sizeArr;
  console.log(width,height);
}
test();

另请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Ignoring_some_returned_values

如果您确实需要每个值,请为每个值声明一个名称:

const [var1,var2,width,height] = sizeArr;

function test() {
  const viewBox = '0 0 24 24'
  const sizeArr = viewBox.split(' ')
  const [var1,var2,width,height]=sizeArr;
  console.log(var1,var2,width,height);
}
test();

const [first, second, width, height] = sizeArr;

let [,,width,height] = arr;
console.log('%s %s', width, height);

您可以简单地将数组解构为已经声明的变量:

let height;
let width;

const viewBox = '0 0 24 24';
const sizeArr = viewBox.split(' ');

[width, height] = sizeArr.slice(2);