Ros*_*ody 5 javascript arrays ecmascript-6 destructure
我如何解构width
,height
如果它们之前已经声明过?
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]
}
Run Code Online (Sandbox Code Playgroud)
hev*_*ev1 10
您可以使用逗号忽略数组中不需要的某些元素:
const [,,width,height] = sizeArr;
Run Code Online (Sandbox Code Playgroud)
const [,,width,height] = sizeArr;
Run Code Online (Sandbox Code Playgroud)
如果let
出于某种原因需要将声明保留在函数顶部,则可以const
从解构中删除。请注意,由于自动插入分号,您将需要在前一行的末尾使用分号。
[,,width,height] = sizeArr;
Run Code Online (Sandbox Code Playgroud)
function test() {
const viewBox = '0 0 24 24'
const sizeArr = viewBox.split(' ')
const [,,width,height]=sizeArr;
console.log(width,height);
}
test();
Run Code Online (Sandbox Code Playgroud)
另见:https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Ignoring_some_returned_values
如果确实需要每个值,请为每个值声明一个名称:
const [var1,var2,width,height] = sizeArr;
Run Code Online (Sandbox Code Playgroud)
[,,width,height] = sizeArr;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
141 次 |
最近记录: |