mercredi 10 février 2021

Looping an array with if and else as well as charAt

I am new to Javascript and I have some experience in C and I cannot figure out what I am doing wrong here. So far Javascript is really confusing and I don't understand it as C is the only programming language I know besides HTML & CSS and I tried these two codes but none of them work.

I am trying to use a for loop and if else statement with charAt. The goal is to look at the first character in an array of names and if the character is a 'j' or 'J' print out "Goodbye" + name and if not print out "Hello" + name. Do I need to convert to ASCII? any insight or recommendations would be great thank you. Here is what I have tried below.

var names = ["Yaakov", "John", "Jen", "Jason", "Paul", "Frank", "Larry", "Paula", "Laura", "Jim"];

for (var i = 0; i < names.length; i++) {
  if (names[i].charAt(0) == 'j' || 'J') {
    console.log("Goodbye " + names[i]);
  } else(names[i].charAt(0) !== 'j' || 'J']) {
  console.log("Hello " + names[i]);
}
}

var names = ["Yaakov", "John", "Jen", "Jason", "Paul", "Frank", "Larry", "Paula", "Laura", "Jim"];

var myFunc = function(letter) {
  for (var i = 0; i < letter.length; i++) {
    if (letter[i].charAt(0) == 'j' || 'J') {
      console.log("Goodbye " + letter[i]);
    }
    if (letter[i].charAt(0) !== 'j' || 'J') {
      console.log("Hello " + letter[i]);
    }
  }
}
myFunc(names);

Aucun commentaire:

Enregistrer un commentaire