如何选择函数承诺的数组元素

问题描述 投票:0回答:1

我有那句话:

const tab = await browser.tabs.query({currentWindow: true,active: true,});

用那句话,

tab
返回一个包含一个元素的对象数组:

tab:
 Array [ {…} ]
​   0: Object { id: 215, index: 0, windowId: 2602, … }
​   length: 1
​   <prototype>: Array []

我可以这样选择数组的第一个元素:

let tab = await browser.tabs.query({currentWindow: true,active: true,});
tab = tab[0]:

但是我想直接选择数组的第一个元素,像这样:

const tab = await browser.tabs.query({currentWindow: true,active: true,})[0];

显然,这是行不通的。但我想要一些这样的东西。

javascript arrays
1个回答
1
投票

您可以将表达式括在括号中,

const tab = (await browser.tabs.query({currentWindow: true,active: true}))[0];

但更清洁的方法是使用

destructuring

const [tab] = await browser.tabs.query({currentWindow: true,active: true});
© www.soinside.com 2019 - 2024. All rights reserved.