开发者问题收集

JavaScript 中使用数组的 While 循环

2021-09-24
2518

我需要 Js 中此代码的帮助。此示例:

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

}

当我执行此操作时,出现信息

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

然后我更改了此行

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

使用此

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

但仍然不起作用,我不知道为什么?

原因是数组中有数字吗?

2个回答

您应该在循环结束时增加 index ,否则您将跳过第一个元素并超过最后一个元素。

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

遍历数组的更好方法是使用 for...of 循环,因此您根本不必使用 index

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

尝试此代码

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)
})
Amit Kakadiya
2021-09-24