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
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
You can use $.inArray() in jQuery
$(function(){
var a = ['red', 'green', 'blue', 'yellow'];
if ($.inArray( "red", a )>=0)
{
alert(a);
}
});
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);
}
Try using $.inArray() as shown.
var a = ['red', 'green', 'blue', 'yellow'];
if($.inArray("red",a) > -1)
{
alert(a);
}
EDIT :-
It 's .includes() Not .include()
https://www.geeksforgeeks.org/javascript-string-includes-method/
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) {
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);
}