简体   繁体   中英

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. 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 .

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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