简体   繁体   中英

the for loop stops after the first true in if

I have a problem with my for loop here

function drawProductUI(array){
    var productsUI = array.map((item) => {
            if (productsInFavArr) {
               for(let j=0; j < productsInFavArr.length; j++){
                    console.log(j);
                    if(productsInFavArr[j].id===item.id)
                    console.log(j);
              }
          }
    });

}
   

productsInFavArr is an array of objects in localstorage

when I console.log(j) before the if statement it gives me the output: 0 1 which is right because I have two objects but when I use it after the if statement it gives me only the first true which is: 0

and the two item.id === the productsInFavArr[j].id so they both are true

and here is the productsInFavArr

let productsInFavArr = [
{
    title: "Sunglasses",
    imgURL: "images/Products/sunglasses.jpg",
    desc: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Aut nulla adipisci fugiat pariatur recusandae repudiandae fuga molestias doloremque itaque obcaecati.",
    price:80,
    id: 1
},
{
    title: "Laptop",
    imgURL: "images/Products/laptop.jpg",
    desc: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Aut nulla adipisci fugiat pariatur recusandae repudiandae fuga molestias doloremque itaque obcaecati.",
    price:100,
    id: 2
}]

thanks

I have a problem with my for loop here

function drawProductUI(array){
    var productsUI = array.map((item) => {
            if (productsInFavArr) {
               for(let j=0; j < productsInFavArr.length; j++){
                    console.log(j);
                    if(productsInFavArr[j].id===item.id)
                    console.log(j);
              }
          }
    });

}
   

productsInFavArr is an array of objects in localstorage

when I console.log(j) before the if statement it gives me the output: 0 1 which is right because I have two objects but when I use it after the if statement it gives me only the first true which is: 0

and the two item.id === the productsInFavArr[j].id so they both are true

and here is the productsInFavArr

let productsInFavArr = [
{
    title: "Sunglasses",
    imgURL: "images/Products/sunglasses.jpg",
    desc: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Aut nulla adipisci fugiat pariatur recusandae repudiandae fuga molestias doloremque itaque obcaecati.",
    price:80,
    id: 1
},
{
    title: "Laptop",
    imgURL: "images/Products/laptop.jpg",
    desc: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Aut nulla adipisci fugiat pariatur recusandae repudiandae fuga molestias doloremque itaque obcaecati.",
    price:100,
    id: 2
}]

thanks

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