gpt4 book ai didi

javascript - 为什么这个循环会重复输出数据?

转载 作者:太空宇宙 更新时间:2023-11-04 03:19:44 25 4
gpt4 key购买 nike

因此,即使我尝试将长度设置为变量并在内部循环中更改它,该循环也会不断重复输出。

这是我的代码:

let testData = {
'title': ['Dark knight', 'Monty python the holy grail', 'the social network'],
'description': ['Batman yelling', 'Random stuff', 'facebook stuff']
};

generateFile(testData);

function generateFile(testData){


for (let i =0; i < testData.title.length; i++){
title = testData.title[i]
for (let j = 0; j < testData.description.length; j++){
description = testData.description[j];
console.log(title);
console.log(description);


}

}
}

这是输出:

Dark knight
Batman yelling
Dark knight
Random stuff
Dark knight
facebook stuff
Monty python the holy grail
Batman yelling
Monty python the holy grail
Random stuff
Monty python the holy grail
facebook stuff
the social network
Batman yelling
the social network
Random stuff
the social network
facebook stuff

它应该只输出一次。

最佳答案

其中有一个嵌套的 for 循环

for (var i=0; i<3; i++){
for (var j=0; j<3; j++){
//inside two loops
}
}

因此外层循环运行三次,但每个外层循环内层循环运行三次。你可以做的来修复它是要么有一个单一的循环,如

for (let i=0; i<testData.titles.length; i++){
console.log(testData.title[i]);
console.log(testData.description[i]);
}

但是更好的选择可能是将数据重组为对象,因为数组是相关的。

let testData=[
{
title: 'Dark knight',
description: 'batman yelling'
}, ...
];

然后做

for (let i=0; i<testData.length; i++){
console.log(testData[i].title);
console.log(testData[i].description);
}

关于javascript - 为什么这个循环会重复输出数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51774519/

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