-1

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

jo_va
  • 13,504
  • 3
  • 23
  • 47
CirLorm
  • 21
  • 8

4 Answers4

1

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");  
   }
ellipsis
  • 12,049
  • 2
  • 17
  • 33
  • Just for the sake of adding useful infos, beware of IE, which lacks the support for `Array.prototype.includes`. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#Browser_compatibility – briosheje Feb 06 '19 at 16:27
  • I worked this way – CirLorm Feb 06 '19 at 16:47
0

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"); 
}
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
0

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"); 
   }
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

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');
}
jo_va
  • 13,504
  • 3
  • 23
  • 47