简体   繁体   English

嵌套循环-这是不好的做法

[英]Nested Loop - Is This Bad Practice

Would it be bad practice to perform a loop like this? 执行这样的循环会不好吗? I'm looping through all cars and appending the text 'new' to each color's name. 我遍历所有汽车,并将“ new”文本附加到每种颜色的名称上。 Each car can have multiple colors. 每辆车可以有多种颜色。

var cars = [
    {
        company: "honda",
        colors: [
            {
                name="burntRed"
            },
            {
                name: "springGreen"
            }
        ]
    },
    {
        company: "ford",
        colors: [
            {
                name="burntOrange"
            },
            {
                name: "black"
            }
        ]
    }
];
        for (var c = 0; c < cars.length; p++) {

            var car = cars[c];

            for (var i = 0; i < cars.colors.length; i++) {
                car.color[i].name += 'new ' + car.color[i].name;
            };
        };

Since the data structure you are iterating over is nested, I do not see another (more performant) way to achieve your task. 由于要迭代的数据结构是嵌套的,因此我看不到另一种(性能更高)的方法来完成您的任务。
Nested iterations are not necessarily a bad thing. 嵌套迭代不一定是一件坏事。 Even many well-known algorithms rely on them. 甚至许多著名的算法都依赖它们。 But you have to be extremely cautious what you execute in the deepest loop, since these commands will be performed very often. 但是您必须非常谨慎地执行最深层的循环,因为这些命令会经常执行。

You may consider a different style to loop over the arrays. 您可能会考虑使用其他样式来遍历数组。 Javascript offer a variety of looping methods of arrays . Javascript提供了各种数组的循环方法。

Here is an example of your proposed functionality, here you can spot the more cleaner style, because of the not more needed index variable. 这是您建议的功能的一个示例,由于不需要更多的索引变量,因此您可以在此处发现更简洁的样式。

By the way, nested loops are inevitable. 顺便说一句,嵌套循环是不可避免的。

 var cars = [{ company: "honda", colors: [{ name: "burntRed" }, { name: "springGreen" }] }, { company: "ford", colors: [{ name: "burntOrange" }, { name: "black" }] }]; cars.forEach(function (car) { car.colors.forEach(function (color) { color.name = 'new ' + color.name; }); }); document.write('<pre>' + JSON.stringify(cars, 0, 4) + '</pre>'); 

A bit late but nested loops are usually bad because they are hard to test and reason about. 有点晚了,但是嵌套循环通常是不好的,因为它们很难测试和推理。 I would go for a more declarative approach: 我将采用一种更具声明性的方法:

const appendStringToColor = (string) => (color) => ({ name: `${color.name} ${string}` });
const appendNewToColor = appendStringToColor('new');
const updateCarWithColor = (car) => ({ ...car, colors: car.colors.map(appendNewToColor) });

const updateCarsColors = (cars) => cars.map(updateCarWithColor);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM