문제

how to check that the variable occurs in an array?

In Example

var X = 5;
var newArray = [1,2,5]

And now something like this

if(X.isin(newArray)
{ document.write( "YES");}

something like this exist? :P

도움이 되었습니까?

해결책

if (newArray.indexOf(X) > -1) {
    // value X exists in newArray
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

다른 팁

You can also use JQuery's inArray() method - it solves compatibility problems. Code:

var X = 5;
var newArray = [1,2,5]
if ($.inArray(X, newArray) > -1) {
    alert('is in array');
}

Fiddle.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top