I tried this...
var age = prompt("your age");
var myArray = new Array(1, 2, 3, 4, 5);
if (age == myArray) {
alert("we know your age");
else {
alert("new age added");
I want to compare the prompt() value to the list in the array
I tried this...
var age = prompt("your age");
var myArray = new Array(1, 2, 3, 4, 5);
if (age == myArray) {
alert("we know your age");
else {
alert("new age added");
I want to compare the prompt() value to the list in the array
Use includes
method to check if age is already in the array or not. Includes check if a given variable present in the array or not.
var age = prompt("your age");
var myArray = new Array(1, 2, 3, 4, 5);
if (myArray.includes(Number(age))) {
alert("we know your age");
}
else {
alert("new age added");
}
You can also use indexOf
method to find the index of the variable in the array. If it is not present, it will output -1
var age = prompt("your age");
var myArray = new Array(1, 2, 3, 4, 5);
if (myArray.indexOf(Number(age))!=-1) {
alert("we know your age");
}
else {
alert("new age added");
}
You can use some to iterate through myArray
and check if any of the element is same as input given by user.
var age = prompt("your age");
var myArray = new Array(1, 2, 3, 4, 5);
if (myArray.some(e=> e == age)) {
alert("we know your age");
} else {
alert("new age added");
}
You can use Array.prototype.includes() which Boolean
. And you also need to parseInt()
age
And try to avoid creating Array like this. Use []
var age = parseInt(prompt("your age"));
var myArray = [1, 2, 3, 4, 5];
if (myArray.includes(age)) {
alert("we know your age");
}
else {
alert("new age added");
}
If you want to check if the age is included in the array, you can use includes
, don't forget to parse the input to a number if it is a string, you can do this with parseInt
, Number
or by prepending a +
in front of the string:
const age = prompt('your age');
const myArray = new Array(1, 2, 3, 4, 5);
if (myArray.includes(Number(age))) {
alert('we know your age');
} else {
alert('new age added');
}