【问题标题】:Why does this loop repeat the output data?为什么这个循环重复输出数据?
【发布时间】: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


【解决方案1】:

你有一个嵌套的 for 循环

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

所以外循环运行 3 次,但内循环每个外循环运行 3 次。 你可以做些什么来解决它要么有一个像

这样的循环
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);
}

【讨论】:

    【解决方案2】:

    您拥有的代码执行以下操作:

    对于testData.title中的每一个元素,遍历testData.description中的每一个元素,输出title+description的组合。

    由于您正在嵌套循环,因此这是预期的。

    如果你想让它为每个标题只显示一个描述,你必须直接选择它。例如:

    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]
            description = testData.description[i];
            console.log(title);
            console.log(description);
        }
    
    }

    这将输出:

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

    它将testData.title 的元素0 与testData.description 的元素0 组合在一起。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-02
      • 2022-01-23
      • 1970-01-01
      • 2021-09-24
      • 1970-01-01
      • 2021-09-07
      相关资源
      最近更新 更多