【发布时间】:2018-08-09 19:29:55
【问题描述】:
因此,即使我尝试将长度设置为变量并在内部循环中更改它,这个循环也会不断重复输出。
这是我的代码:
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
而且应该只输出一次。
【问题讨论】:
-
因为你不只有“这个循环”,你有两个嵌套循环。为什么?
-
可能想摆脱内循环。不知道你到底想在这里做什么
-
您的循环是嵌套的,因此对于外循环的每次迭代,内循环都会完全执行。您需要同时迭代两个数组的并行循环..
标签: javascript node.js loops