gpt4 book ai didi

javascript - 具有重复结构的数组

转载 作者:行者123 更新时间:2023-12-01 00:18:40 26 4
gpt4 key购买 nike

我正在创建一个脚本来显示我的数组的键,在第一次尝试中工作得很好,但是当我添加一个while block 时,他没有执行并返回了这个错误:

classificacao-v2.js:128 Uncaught TypeError: Cannot read property 'Period' of undefined
at classificacao-v2.js:128

意识到我的问题在于变量“n”显示为未定义,因此我为每个结构创建了具有不同名称的其他变量。我想知道是否可以更有效地重写它,而不必重复每个 block 。

let GoldemStates = [{Period: ' 1°',Points:'300'},
{Period: ' 2°',Points:'250'},
{Period: ' 3°', Points:'155'}]

let Chicago = [{Period: ' 1°',Points:'100'},
{Period: ' 2°',Points:'420'},
{Period: ' 3°', Points:'350'}]

let Broklyn = [{Period: ' 1°',Points:'300'},
{Period: ' 2°',Points:'250'},
{Period: ' 3°', Points:'155'}]

// Show the Teams

icons('','Match Results ','div_titulo')

let n = 0
icons('golden','Golden States', 'destaque_golden') //Team Title (Symbol, Team Name, CSS)

//Goldem States Statistics
do {
icons('clock',GoldemStates[n].Period + ' Period | ' + 'Points ' + GoldemStates[n].Points ,'texto') // // Show period and points
n ++
} while (n < GoldemStates.length);
let d = 0 // <-------- CHANGE WHICH WOULD NEED

//Chicago Bulls Statistics
icones('bulls','Chicago Bulls', 'destaque_bulls')//Team Title (Symbol, Team Name, CSS)
do {
icons('clock',Chicago[d].Period + ' Period | ' + 'Points ' + Chicago[d].Points ,'texto')// Show period and points
d ++
} while (d < Chicago.length);

控制台输出 Output

最佳答案

我认为,如果将迭代留给内置方法的数组,您的代码可能会更简单、更短且更易于阅读。这样您就无需使用迭代变量并访问每个项目:

GoldemStates.forEach( 
item => icons('clock',item.Period + ' Period | ' + 'Points ' + item.Points ,'texto')
)

但我们可以做得更好。由于所有团队的渲染效果完全相同,因此我们可以构建一个渲染单个项目的函数,然后让专门用于迭代的方法完成其工作。这样你的代码只负责渲染,内置方法负责迭代、概念分离:

const renderTeam = team => icons('clock',team.Period + ' Period | ' + 'Points ' + team.Points ,'texto')
// Render part
icons('golden','Golden States', 'destaque_golden') //Team Title (Symbol, Team Name, CSS)
GoldemStates.forEach(renderTeam)

icons('bulls','Chicago Bulls', 'destaque_bulls')//Team Title (Symbol, Team Name, CSS)
Chicago.forEach(renderTeam)

关于javascript - 具有重复结构的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59584711/

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