3

How to write if include? condition in JavaScript?

My sample code is here:

var a = ['red', 'green', 'blue', 'yellow'];
if (a.include("red" ))
{ 
    alert(a);
}

It gives the following error:

SyntaxError: missing : in conditional expression
Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
Siva KB
  • 357
  • 1
  • 6
  • 19

5 Answers5

3

You can use $.inArray() in jQuery

$(function(){
var a = ['red', 'green', 'blue', 'yellow'];
if ($.inArray( "red", a )>=0)
{ 
    alert(a);
}
});

Demo

Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
3

plain vanilla javascript

you can use some to check for the existence

The some() method tests whether some element in the array passes the test implemented by the provided function.

var result = ['red', 'green', 'blue', 'yellow'].some(function(item,index,arr){
        return item === 'red'
});

if (result === true)
{ 
    alert(a);
}
Prabhu Murthy
  • 9,031
  • 5
  • 29
  • 36
2

Try using $.inArray() as shown.

var a = ['red', 'green', 'blue', 'yellow'];
if($.inArray("red",a) > -1) 
{
  alert(a);
}

EDIT :-

DEMO

Kartikeya Khosla
  • 18,743
  • 8
  • 43
  • 69
2

It 's .includes() Not .include()

https://www.geeksforgeeks.org/javascript-string-includes-method/

XER0ZZ
  • 696
  • 6
  • 5
1

I think you are trying to find a ruby alternative. Are you checking whether red is a member of array ? You can use Array.indexOf()

then you may do it like

if (a.indexOf("red" )=!-1) {

Sample code below:

var a = ['red', 'green', 'blue', 'yellow'];

//will return -1 if not found in array. otherwise will give you the index
var indexOfRed = a.indexOf("red");

if (indexOfRed!=-1)
{ 
    alert("red was found at index - "+indexOfRed);
}
Mithun Satheesh
  • 27,240
  • 14
  • 77
  • 101