简体   繁体   English

如何解构这个数组

[英]How to destructure this Array

How do I destructure width and height if they have been declared before?如果之前已经声明过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]
}

You can use a comma to ignore certain elements of the array that you do not need:您可以使用逗号忽略数组中不需要的某些元素:

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();

If you need to keep the let declarations at the top of the function for some reason, you can remove the const from destructuring.如果出于某种原因需要将let声明保留在 function 的顶部,则可以从解构中删除const Note that you will need a semicolon at the end of the preceding line due to automatic semicolon insertion.请注意,由于自动插入分号,您需要在前一行的末尾添加一个分号。

[,,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();

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

If you do need every value, declare a name for each one:如果您确实需要每个值,请为每个值声明一个名称:

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;

You can simply destructure the array into the already-declared variables:您可以简单地将数组解构为已声明的变量:

let height;
let width;

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

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

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

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