【问题标题】:While-loop with arrays in JavaScript在 JavaScript 中使用数组的 While 循环
【发布时间】:2021-11-17 18:56:00
【问题描述】:

我需要有关 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;} 

还是不行,不知道为什么?

是数组中有数字的原因吗?

【问题讨论】:

    标签: javascript arrays loops while-loop


    【解决方案1】:

    你应该在循环结束时增加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);
    }
    

    【讨论】:

      【解决方案2】:

      试试这个代码

          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)
      })
      

      【讨论】:

      • 答案应该解释对代码所做的更改以及它们如何帮助 OP,
      • 请查看代码中的cmets
      猜你喜欢
      • 2020-12-01
      • 2015-02-20
      • 1970-01-01
      • 2020-10-03
      • 2012-02-26
      • 2020-08-29
      • 2018-03-30
      • 2020-08-14
      • 2014-04-30
      相关资源
      最近更新 更多