gpt4 book ai didi

javascript - 数组嵌套循环无法按预期工作

转载 作者:行者123 更新时间:2023-12-04 00:57:37 24 4
gpt4 key购买 nike

我正在努力完成以下...

给定数组蛋糕:

const cakes = [
{id: 1, name: 'chocolate'},
{id: 2, name: 'strawberry'},
{id: 3, name: 'mint'}
]

数组“最喜欢的蛋糕”为:

const favCakes = [
{id: 1, cakeId: 1},
{id: 2, cakeId: 2}
]

我想在控制台上记录 FAVORITE CAKES 和 NOT FAVORITE CAKES,所以我希望得到这样的结果:

FAVORITE CAKES: 'chocolate'
FAVORITE CAKES: 'strawberry'
NOT FAVORITE CAKES: 'mint'

但正如您从下面的代码片段中看到的那样,它并没有像预期的那样工作。我究竟做错了什么?感谢您的帮助。

const cakes = [
{id: 1, name: 'chocolate'},
{id: 2, name: 'strawberry'},
{id: 3, name: 'mint'}
]

// favorite cakes for logged in user
const favCakes = [
{id: 1, cakeId: 1},
{id: 2, cakeId: 2}
]

for (const cake of cakes) {
for (const fav of favCakes) {
if (cake.id === fav.cakeId) {
console.log('FAVORITE CAKE: ', cake.name )
}
else if (cake.id !== fav.cakeId) {
console.log('NOT FAVORITE CAKE: ', cake.name )
}
}
}

最佳答案

您过早地检查不喜欢的内容。只有浏览完所有收藏夹后才能确定不喜欢:

for (const cake of cakes) {
let isFavorite = false; // assume

for (const fav of favCakes) {
if (cake.id === fav.cakeId) {
console.log('FAVORITE CAKE: ', cake.name)
isFavorite = true;
break;
}
}

if ( ! isFavorite ) {
console.log( 'NOT FAVORITE CAKE: ', cake.name )
}

}

关于javascript - 数组嵌套循环无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61672759/

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