gpt4 book ai didi

javascript - ES6解构以从内部数组中获取第n个项目

转载 作者:行者123 更新时间:2023-11-30 07:19:51 25 4
gpt4 key购买 nike

我的 React 项目中有一个数组处于我的状态。像这样的东西:

state = {
cats : [
{cid : 1 , value : 1}
{cid : 2 , value : 3}
{cid : 3 , value : 4}
],
curpage : 3
}

现在我想要的是使用解构字符串获取数组cats第n 项。我试过了

const { cat : {cats[id]} } = this.state;

 const { cats[id] } = this.state;

最佳答案

您可以使用 computed object property with destructuring获取第 n 数组项并将其分配给变量:

const state = {
cats : [
{cid : 1 , value : 1},
{cid : 2 , value : 3},
{cid : 3 , value : 4}
],
curpage : 3
}

const n = 2;

const { cats: { [n]: nthCat} } = state;

console.log(nthCat)

或者,如果 n 很小并且您事先知道它,您可以 ignore the values你不需要:

const state = {
cats : [
{cid : 1 , value : 1},
{cid : 2 , value : 3},
{cid : 3 , value : 4}
],
curpage : 3
}

const { cats: [,,thirdCat] } = state;

console.log(thirdCat)

关于javascript - ES6解构以从内部数组中获取第n个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54417373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com