gpt4 book ai didi

javascript - 如何在一行中从单独的解构属性进行解构?

转载 作者:行者123 更新时间:2023-12-03 13:41:19 25 4
gpt4 key购买 nike

const { navigation, currentScreen, childIndex } = this.state
const screen = navigation[currentScreen]

如何用一行代码而不是两行代码编写此代码?

最佳答案

{ [currentScreen]: screen } ,确保提取 currentScreen事先:

const state = { navigation: { foo: 'val' }, currentScreen: 'foo' };

const { navigation, currentScreen, childIndex, navigation: { [currentScreen]: screen } } = state
console.log(screen);

也就是说,它确实很难阅读。我强烈建议您使用当前版本。仅在 actually code-golfing 时编写高尔夫球线代码,否则最好在几乎所有情况下优化可读性。

数组示例 navigation而不是对象:

const state = { navigation: ['val1', 'val2', 'val3'], currentScreen: 1 };

const { navigation, currentScreen, childIndex, navigation: { [currentScreen]: screen } } = state
console.log(screen);

关于javascript - 如何在一行中从单独的解构属性进行解构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59425500/

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