답변:
이 시도:
if(blockedTile.indexOf("118") != -1)
{
// element found
}
if(!!~blockedTile.indexOf('118))이 방법이 항상 true를 돌려줍니다 결과> -1과 거짓 === 결과의 경우 -1 경우
indexOf()리터럴 배열에도 적용될 수 있습니다 (예 :) if (-1 == [84, 116].indexOf(event.keyCode)). Chrome 37.0.2062.122에서 테스트되었습니다.
indexOf(…) >= 0합니다. 차이가 없습니다 그리고 난 습관으로 집어 어디에서 잊지
앞서 언급했듯이, 브라우저가을 지원 indexOf()하면 훌륭합니다! 그렇지 않은 경우,이를 pollyfil하거나 lodash / underscore 와 같은 유틸리티 벨트에 의존해야 합니다 .
이 새로운 ES2016 추가 사항 을 추가하고 싶었습니다 (이 질문을 계속 업데이트하십시오).
if (blockedTile.includes("118")) {
// found element
}
그것은 크로스 브라우저 준수 와 데이터가 정렬되어있는 경우 이진 검색을 수행 할 수 있습니다.
_.indexOf (array, value, [isSorted]) 배열에서 값을 찾을 수있는 인덱스를 반환하거나 값이 배열에 없으면 -1을 반환합니다. 누락되지 않은 경우 native indexOf 함수를 사용합니다. 큰 배열로 작업 중이고 배열이 이미 정렬되어 있다는 것을 알고 있다면 isSorted에 대해 더 빠른 이진 검색을 사용하려면 true를 전달하십시오.
//Tell underscore your data is sorted (Binary Search)
if(_.indexOf(['2','3','4','5','6'], '4', true) != -1){
alert('true');
}else{
alert('false');
}
//Unsorted data works to!
if(_.indexOf([2,3,6,9,5], 9) != -1){
alert('true');
}else{
alert('false');
}
일부 브라우저는을 지원 Array.indexOf()합니다.
그렇지 않은 경우 Array프로토 타입을 통해 오브젝트를 확장 할 수 있습니다 .
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(searchElement /*, fromIndex */)
{
"use strict";
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (len === 0)
return -1;
var n = 0;
if (arguments.length > 0)
{
n = Number(arguments[1]);
if (n !== n) // shortcut for verifying if it's NaN
n = 0;
else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
if (n >= len)
return -1;
var k = n >= 0
? n
: Math.max(len - Math.abs(n), 0);
for (; k < len; k++)
{
if (k in t && t[k] === searchElement)
return k;
}
return -1;
};
}
소스 .
취향에 맞게 사용하십시오.
var blockedTile = [118, 67, 190, 43, 135, 520];
// includes (js)
if ( blockedTile.includes(118) ){
console.log('Found with "includes"');
}
// indexOf (js)
if ( blockedTile.indexOf(67) !== -1 ){
console.log('Found with "indexOf"');
}
// _.indexOf (Underscore library)
if ( _.indexOf(blockedTile, 43, true) ){
console.log('Found with Underscore library "_.indexOf"');
}
// $.inArray (jQuery library)
if ( $.inArray(190, blockedTile) !== -1 ){
console.log('Found with jQuery library "$.inArray"');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
2019 년에하는 가장 좋은 방법은 .includes()
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
[1, 2, 3].includes(1, 2); // false
첫 번째 매개 변수는 당신이 찾고있는 것입니다. 두 번째 매개 변수는 검색을 시작할이 배열의 색인 위치입니다.
여기에 크로스 뷰가 필요한 경우 많은 레거시 답변이 있습니다.
includes솔루션은 Kutyel (2016), Сергей Савельев (2017) 및 Krunal Limbad (2018)에서 동일하게 자세한 예와 참조로 답변됩니다.
이미 위에서 답변했지만 공유하고 싶었습니다.
IE에서는 작동하지 않습니다. @Mahmoud를 언급 해 주셔서 감사합니다.
var array1 = [1, 2, 3];
console.log(array1.includes(2));
// expected output: true
var pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat'));
// expected output: true
console.log(pets.includes('at'));
// expected output: false
여기에 몇 가지 참조가 있습니다. 그들은 또한 위의 Polyfill을 가지고 있습니다.
Array.includes()ES7 (ECMAScript 2017)에 도입되었으며 이전 브라우저에서는 작동하지 않습니다. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
배열이 최상의 솔루션이 아닌 것처럼 보이기 때문에 다른 데이터 구조를 사용합니다.
배열 대신 객체를 해시 테이블로 사용하십시오.
( jsbin 에도 게시 됨 )
var arr = ["x", "y", "z"];
var map = {};
for (var k=0; k < arr.length; ++k) {
map[arr[k]] = true;
}
function is_in_map(key) {
try {
return map[key] === true;
} catch (e) {
return false;
}
}
function print_check(key) {
console.log(key + " exists? - " + (is_in_map(key) ? "yes" : "no"));
}
print_check("x");
print_check("a");
콘솔 출력 :
x exists? - yes
a exists? - no
그것은 간단한 해결책입니다. 객체 지향 접근 방식에 더 관심이 있다면 Google에서 "js hashtable" 을 검색하십시오 .
이전 브라우저와 가장 호환되는 IMHO
Array.prototype.inArray = function( needle ){
return Array(this).join(",").indexOf(needle) >-1;
}
var foods = ["Cheese","Onion","Pickle","Ham"];
test = foods.inArray("Lemon");
console.log( "Lemon is " + (test ? "" : "not ") + "in the list." );
배열 사본을 CSV 문자열로 변환하면 이전 브라우저에서 문자열을 테스트 할 수 있습니다.
['Lemon Pie'].inArray('Lemon')돌아올 것이다True 합니다. 당신은 ,그것을 피하기 위해 바늘을 감쌀 수도 있고 정규 표현식을 사용하여 마찬가지로 할 수도 있지만 ,비슷한 거짓 양성 이유 보다 더 모호한 것을 사용하는 것이 바람직 |합니다. 데이터 셋에 따라 다릅니다.
배열 예제에서는 PHP와 동일합니다 (in_array)
var ur_fit = ["slim_fit", "tailored", "comfort"];
var ur_length = ["length_short", "length_regular", "length_high"];
if(ur_fit.indexOf(data_this)!=-1){
alert("Value is avail in ur_fit array");
}
else if(ur_length.indexOf(data_this)!=-1){
alert("value is avail in ur_legth array");
}
var myArray = [2,5,6,7,9,6];
myArray.includes(2) // is true
myArray.includes(14) // is false
includes. 이 답변은 그에 비해 추가 가치를 어떻게 제공합니까?
아래 코드를 시도해 볼 수 있습니다. http://api.jquery.com/jquery.grep/를 확인하십시오.
var blockedTile = new Array("118", "67", "190", "43", "135", "520");
var searchNumber = "11878";
arr = jQuery.grep(blockedTile, function( i ) {
return i === searchNumber;
});
if(arr.length){ console.log('Present'); }else{ console.log('Not Present'); }
arr.length가 0보다 크면 문자열이 있고 그렇지 않으면 존재하지 않는지 확인하십시오.
가장 간단한 방법은 다음과 같습니다.
(118 in blockedTile); //is true