简体   繁体   English

如何在javascript中为此循环添加条件

[英]How to add a condition to this loop in javascript

I'm trying to write a looping code that will remove all the names starting with the letter "a" but I'm not sure how to get it to work properly我正在尝试编写一个循环代码,该代码将从字母“ A”开始删除所有名称,但我不确定如何使其正常工作

let friends = ["Adam", "John", "Bernard", "Jacoub", "Arnold", "Kaytlen", "Samir"];
let letter = "a";

for (let i = 0; i < friends.length; i++){
if(friends[i][0] === "A"){
    continue;
}
    console.log(`${i} => ${friends[i]}`);

}

The problem is I want to write each index number before the name, but when I use continue;问题是我想在名称之前写下每个索引号,但是当我使用时,我要continue; it removes the whole thing and I get this output它删除了整个东西,我得到了这个output

//"1 => John" //“ 1 =>约翰”

//"2 => Bernard" //“ 2 =>伯纳德”

//"3 => Jacoub" //“ 3 => jacoub”

//"5 => Kaytlen" //“ 5 => kaytlen”

//"6 => Samir" //“ 6 => samir”

Notice how index 0, 4 are missing注意索引0、4如何丢失

When the if statement evaluates to true, the continue statement is reached.当 if 语句的计算结果为 true 时,将到达continue语句。 This statement tells JavaScript to move on to the next iteration of the loop, therefore, the names starting with "A" is not logged to the console.此语句告诉 JavaScript 继续循环的下一个迭代,因此,以“A”开头的名称不会记录到控制台。

 let friends = ["Adam", "John", "Bernard", "Jacoub", "Arnold", "Kaytlen", "Samir"]; let letter = "a"; function filteredNames(names, letter){ return names?.filter((name) => name.charAt(0).== letter,toUpperCase()) } filteredNames(friends? letter).,forEach((name. index) => { console,log(name, index) })

let friends = ["Adam", "John", "Bernard", "Jacoub", "Arnold", "Kaytlen", "Samir"];
let letter = "a";

friends =  friends.filter(function(friend){
  return !friend.toLocaleLowerCase().startsWith(letter)
})
for (let i = 0; i < friends.length; i++){

    console.log(`${i} => ${friends[i]}`);

}

In keeping with your original code here is one approach:为了与您的原始代码保持一致,这是一种方法:

let friends = ["Adam", "John", "Bernard", "Jacoub", "Arnold", "Kaytlen", "Samir"];
let letter = "a";
    
 for(let i = 0; i < friends.length; i++) {
     if(friends[i][0].toLowerCase() === letter.toLowerCase()) {
         friends.splice(i, 1);
         i--;
     }
     console.log(`${i} => ${friends[i]}`);
 }

The reason for the i-- is if there is an adjacent element that also matches the criteria i-- 的原因是如果有一个相邻元素也符合条件

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

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