简体   繁体   English

在 JavaScript 中使用 arrays 进行 while 循环

[英]While-loop with arrays in JavaScript

I need help with this code in Js.我需要 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. seventh_lesson.js:203 Uncaught TypeError: 无法在 seventh_lesson.js:203 处读取未定义的属性(读为“0”)。

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?数组中有数字的原因是什么?

You should increase the index at the end of the loop, otherwise you skip the first element and overshoot the last one.您应该在循环结束时增加index ,否则您将跳过第一个元素并超过最后一个元素。

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...of循环,因此您根本不必使用index

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

Try this code试试这个代码

    let friends = ["Ahmed", "Sayed", "Ali", 1, 2, "Mahmoud", "Amany"];
    let index = -1; // Here define index position is -1 because in the while loop first increase index
    
    
    
    // // Output
    // "1 => Sayed"
    // "2 => Mahmoud"
    
    while(index < friends.length-1){
        index++;
         
        if ( typeof friends[index] === "number"){
            continue;
        }
        if (friends[index].charAt(0) === "A"){ // Here used charAt(0) is meance it will check only first letter is A or not If find a then it will continue 
            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)
})

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

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