Home > Back-end >  I can't understand why this won't work (specifying a range within an array / if statement)
I can't understand why this won't work (specifying a range within an array / if statement)

Time:02-28

var guestList = ['Gabe', 'name2', 'name3', 'name4', 'name5']

var guestName = prompt('Hello, what is your name')

var range = guestList.slice(0, guestList.length)

if (guestList.includes(range)) {
    alert(`Hello ${guestName} and welcome to EVENT NAME`)


} else {
    alert(`Hello ${guestName}, you are not on the guest list`)
}

CodePudding user response:

Is this what you want?

var guestList = ['Gabe', 'name2', 'name3', 'name4', 'name5']

var guestName = prompt('Hello, what is your name')

if (guestList.includes(guestName)) {
    alert(`Hello ${guestName} and welcome to EVENT NAME`)
} else {
    alert(`Hello ${guestName}, you are not on the guest list`)
}

CodePudding user response:

I suppose this works fine:

var guestList = ['Gabe', 'name2', 'name3', 'name4', 'name5']

var guestName = prompt('Hello, what is your name')

if (guestList.includes(guestName)) { alert("Hello"  guestName  "and welcome to EVENT NAME")

} else { alert("Hello "  guestName ", you are not on the guest list") }

CodePudding user response:

Remove range because it's useless and replace range in this line with guestName

if (guestList.includes(guestName)) {....

Prompt() returns a value which is whatever the user entered.

var guestList = ['Gabe', 'name2', 'name3', 'name4', 'name5']

var guestName = prompt('Hello, what is your name')

/* Add this line if you want the comparison
to be case insensitive 
*/
// guestList = guestList.map(name => name.toLowerCase());

/* And replace guestName with
guestName.toLowerCase() in the "if"
statement as well.
*/
if (guestList.includes(guestName)) {
  alert(`Hello ${guestName} and welcome to EVENT NAME`)
} else {
  alert(`Hello ${guestName}, you are not on the guest list`);
}

CodePudding user response:

Take a look on that line of your code var range = guestList.slice(0, guestList.length). Now range is a sub-array of guestList and you´re trying to verifacate in guestListif it includes the element range that is not true.

I think you´re trying to do this:

var guestList = ['Gabe', 'name2', 'name3', 'name4', 'name5']

var guestName = prompt('Hello, what is your name')

if (guestList.includes(guestName)) {
    alert(`Hello ${guestName} and welcome to EVENT NAME`)


} else {
    alert(`Hello ${guestName}, you are not on the guest list`)
}

  • Related