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
0

5 Answers 5

3

You can use $.inArray() in jQuery

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

Demo

Sign up to request clarification or add additional context in comments.

Comments

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);
}

Comments

2

Try using $.inArray() as shown.

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

EDIT :-

DEMO

Comments

2

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

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

Comments

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);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.