简体   繁体   中英

For loop to check the first letter in an array

I am trying to use a for loop to loop through an array and check the first letter of each word in the array and check to see if it starts with an M, but I can't seem to figure out how to correctly set that up.

So far I have this:

for (var animalsName = cats[0]; animalsName <= cats; animalsName++){
    if (animalsName.charAt(0) == 'M') {
        console.log("No treat for " + animalsName + ".");
    } else {
        console.log(animalsName + " loved their treat!");
    }
}
for (let i = 0; i < cats.length; i += 1) {
  if (cats[i].charAt(0).toLowerCase() === 'm') {
    // do whatever you want
  }
}

This will loop over the cats array and check the first letter-- charAt(0) --of each element in the array. If the first letter, converted to lower case, is 'm', then you do whatever you want.

You are very close.

I have made minor change in the for loop to iterate correctly and fetch the first character of the animal name.

 var cats = []; cats.push('mname1'); cats.push('tname1'); cats.push('mname2'); cats.push('Mname3'); for (var index = 0; index < cats.length; index++){ var animalsName = cats[index]; if (animalsName.substr(0,1).toLowerCase() === 'm') { console.log("No treat for " + animalsName + "."); } else { console.log(animalsName + " loved their treat!"); } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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