gpt4 book ai didi

javascript - 为什么 Javascript 对象显示出如此多的层次结构?如何正确声明和访问?

转载 作者:太空宇宙 更新时间:2023-11-04 02:08:30 24 4
gpt4 key购买 nike

export interface NowChannelInterface {
id: number;
name: string;
isSelected: Boolean;
}

export interface NowChannellistInterface {
nowChannelList: NowChannelInterface[];
}

const initialState: NowChannellistInterface = {
nowChannelList: [
{
id: 0,
name: 'CNN',
isSelected: true
},
{
id: 1,
name: 'BBC',
isSelected: true
},
{
id: 2,
name: 'NDTV',
isSelected: true
},
{
id: 3,
name: 'QTV',
isSelected: true
}
]
};

state: NowChannellistInterface = initialState;
const chx: any = { id: 1, name: 'BBC', isSelected: true};
cur_channel: NowChannelInterface = chx;
channels: any = state
console.log(channels);

然后将initialState复制到 channel 中,关于替代声明方式的任何建议也是受欢迎的,但请注意,我必须将上述两个保留为接口(interface)而不是类,以便能够将其与可观察量一起使用。

然后在控制台中,当我尝试使用时:

enter image description here

最佳答案

接口(interface)是 Typescript 的编译时功能,它支持强大的工具、静态类型检查以及以干净的声明方式表达 API 的能力。与 TypeScript 的所有方面一样,它们不会在编译的输出中显现出来。输出只是 JavaScript。

此外,您拥有的是分层数据结构。它是一个 ObjectArray。调试器允许扩展数组的内容,然后使用方便的、基于树的可视化方法扩展每个对象的内容。只需使用成员访问符号 - .property['property'],无需调试器即可获得相同的信息。

减少此类嵌套的唯一方法是降低嵌套程度。

但是,我不确定您为什么要这样做。

您的代码看起来非常合理。您的接口(interface)名称风格很差,应该删除 Interface 后缀,因为它非常不惯用,但除此之外,我没有看到值得关注的具体原因。

值得注意的一件事是,您似乎有额外级别的属性嵌套。这使得 API 使用起来有点尴尬。如果没有看到更多代码,很难说,但你可能有类似的东西

const channels = { nowChannelList: initialState };

某处。

这可以重写为

const channels = { nowChannelList: initialState.nowChannelList };

channel 本身可以简化为

const channels = initialState.nowChannelList;

但我认为你这样写是有原因的。

下面是一个较少嵌套代码的示例,只是为了澄清

const initialState = {
nowChannelList: [
{
id: 0,
name: 'CNN',
isSelected: true
},
{
id: 1,
name: 'BBC',
isSelected: true
},
{
id: 2,
name: 'NDTV',
isSelected: true
},
{
id: 3,
name: 'QTV',
isSelected: true
}
]
};

const channels = initialState.nowChannelList;

console.log(channels);

关于javascript - 为什么 Javascript 对象显示出如此多的层次结构?如何正确声明和访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43313888/

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