Home > database >  While-loop with arrays in JavaScript
While-loop with arrays in JavaScript

Time:09-24

I need help with this code in Js. this example :

let friends = ["Ahmed", "Sayed", "Ali", 1, 2, "Mahmoud", "Amany"];
let index = 0;
let counter = 0;



// // Output
// "1 => Sayed"
// "2 => Mahmoud"



while(index < friends.length){
    index  ;
    if ( typeof friends[index] === "number"){
        continue;
    }
    if (friends[index][counter] === "A"){
        continue;
    }
    console.log(friends[index]);

}

When I did it the massage appear to me,

seventh_lesson.js:203 Uncaught TypeError: Cannot read properties of undefined (reading '0') at seventh_lesson.js:203.

and then I changed this line

if (friends[index][counter] === "A"){continue;
}

with this

if (friends[index].startsWith("A")){continue;} 

and still doesn’t work, I don’t know why?

Is the reason there are numbers in the array?

CodePudding user response:

You should increase the index at the end of the loop, otherwise you skip the first element and overshoot the last one.

while(index < friends.length){
    if ( typeof friends[index] === "number"){
        continue;
    }
    if (friends[index][counter] === "A"){
        continue;
    }
    console.log(friends[index]);
    index  ;
}

A better way to iterate through the array would be a for...of loop, so you won't have to use the index at all.

for(const friend of friends)
    if ( typeof friend === "number"){
        continue;
    }
    if (friend[counter] === "A"){
        continue;
    }
    console.log(friend);
}

CodePudding user response:

Try this code

    let friends = ["Ahmed", "Sayed", "Ali", 1, 2, "Mahmoud", "Amany"];
    let index = -1;
    
    
    
    // // Output
    // "1 => Sayed"
    // "2 => Mahmoud"
    
    while(index < friends.length-1){
        index  ;
         
        if ( typeof friends[index] === "number"){
            continue;
        }
        if (friends[index].charAt(0) === "A"){
            continue;
        }
       
        console.log(friends[index]);
    
    }

OR 

let friends = ["Ahmed", "Sayed", "Ali", 1, 2, "Mahmoud", "Amany"];
friends.filter((o)=>{
  if(typeof(o)!="number"&&!o.startsWith("A"))
  console.log(o)
})
  • Related