Home > Enterprise >  a For loop with conditional statment within an array
a For loop with conditional statment within an array

Time:12-17

Can please anyone help me, I tried different conditions but, constantlly I am creating and infinite loop, and I am not sure how to figure it out.

Using for loop structure how to add a conditional statement within the array that will loop through the array and determine which one is my favourite car

const vehicles = ["Audi", "BMW", "Seat", "Opel", "Peugeot"]; 
let fav = "Seat" 
for (let i = 0; i < vehicles.length; i  ){
    console.log(`Not my fav ${vehicles[i]}`);
}

The Audi is not my favourite vehicle
The BMW is not my favourite vehicle
The Seat IS my favourite vehicle
The Opel is not my favourite vehicle The Peugeot is not my favourite vehicle*/

Sorry, I am just a beginner, I will really appreciate any hints or solutions to this task.

CodePudding user response:

In the loop you have to write:

if (vehicles[i] == "Seat") {
    console.log("The Seat is my favorite vehicle");
} else {
    console.log("The ${vehicles[i]} is not my favorite vehicle.")
}

You can also create a list of favorite vehicles and check whether vehicles[i] is in the favorite vehicles list.

var favorite_vehicles = ["Seat", "Audi", "ETC"]

for (let i = 0; i < vehicles.length; i  ) {
    if (favorite_vehicles.includes(vehicles[i]) == true) {
        console.log("The ${vehicles[i]} is my favorite vehicle.")
} 
    else{
        console.log("The ${vehicles[i]} is not my favorite vehicle.")
}
}

  • Related