항목이 JavaScript 어레이에 있는지 확인하는 가장 좋은 방법은? [복제하다

StackOverflow https://stackoverflow.com/questions/143847

  •  02-07-2019
  •  | 
  •  

문제

이 질문은 이미 여기에 답이 있습니다.

객체가 배열에 있는지 여부를 찾는 가장 좋은 방법은 무엇입니까?

이것이 내가 아는 가장 좋은 방법입니다.

function include(arr, obj) {
    for(var i=0; i<arr.length; i++) {
        if (arr[i] == obj) return true;
    }
}

include([1,2,3,4], 3); // true
include([1,2,3,4], 6); // undefined
도움이 되었습니까?

해결책

ECMAScript 2016에서 사용할 수 있습니다 includes()

arr.includes(obj);

IE 또는 기타 구형 브라우저를 지원하려면 :

function include(arr,obj) {
    return (arr.indexOf(obj) != -1);
}

편집 : IE6, 7 또는 8에서는 작동하지 않습니다. 가장 좋은 해결 방법은 존재하지 않는 경우 직접 정의하는 것입니다.

  1. 모질라 (ECMA-262) 버전 :

      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)
            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;
      };
    
    }
    
  2. 다니엘 제임스버전 :

    if (!Array.prototype.indexOf) {
      Array.prototype.indexOf = function (obj, fromIndex) {
        if (fromIndex == null) {
            fromIndex = 0;
        } else if (fromIndex < 0) {
            fromIndex = Math.max(0, this.length + fromIndex);
        }
        for (var i = fromIndex, j = this.length; i < j; i++) {
            if (this[i] === obj)
                return i;
        }
        return -1;
      };
    }
    
  3. Roosteronacid버전 :

    Array.prototype.hasObject = (
      !Array.indexOf ? function (o)
      {
        var l = this.length + 1;
        while (l -= 1)
        {
            if (this[l - 1] === o)
            {
                return true;
            }
        }
        return false;
      } : function (o)
      {
        return (this.indexOf(o) !== -1);
      }
    );
    

다른 팁

jQuery를 사용하는 경우 :

$.inArray(5 + 5, [ "8", "9", "10", 10 + "" ]);

자세한 내용은: http://api.jquery.com/jquery.inarray/

먼저 구현 indexOf 아직 가지고 있지 않은 브라우저의 경우 JavaScript에서. 예를 들어, 참조하십시오 Erik Arvidsson의 배열 엑스트라 (또한 관련 블로그 게시물). 그런 다음 사용할 수 있습니다 indexOf 브라우저 지원에 대해 걱정하지 않고. 여기에 약간 최적화 된 버전이 있습니다 indexOf 구현:

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (obj, fromIndex) {
        if (fromIndex == null) {
            fromIndex = 0;
        } else if (fromIndex < 0) {
            fromIndex = Math.max(0, this.length + fromIndex);
        }
        for (var i = fromIndex, j = this.length; i < j; i++) {
            if (this[i] === obj)
                return i;
        }
        return -1;
    };
}

모든 반복을 찾을 필요가 없도록 길이를 저장하도록 변경되었습니다. 그러나 그 차이는 크지 않습니다. 덜 범용 기능이 더 빠를 수 있습니다.

var include = Array.prototype.indexOf ?
    function(arr, obj) { return arr.indexOf(obj) !== -1; } :
    function(arr, obj) {
        for(var i = -1, j = arr.length; ++i < j;)
            if(arr[i] === obj) return true;
        return false;
    };

표준 기능을 사용하고 실제로 필요한 경우 이런 종류의 미세 최적화를 선호합니다. 그러나 당신이 미세 최적화에 관심이 있다면 나는 그것을 적응시켰다 벤치 마크 그 수탉은 주석에 연결되어 있습니다 배열에서 검색 벤치 마크. 그들은 꽤 조잡하지만 전체 조사는 다른 유형, 길이가 다른 어레이 및 다른 장소에서 발생하는 물체를 찾는 어레이를 테스트 할 것입니다.

배열이 분류되지 않은 경우, 위에서 언급 한 인덱스를 사용하는 것 외에도 같은 방법은 더 나은 방법이 없습니다. 배열이 정렬되면 이진 검색을 수행 할 수 있습니다.

  1. 배열의 중간 요소를 선택하십시오.
  2. 원하는 요소가 선택한 요소보다 큽니까? 그렇다면 배열의 하단 절반을 제거했습니다. 그렇지 않다면, 당신은 상단 절반을 제거했습니다.
  3. 배열의 나머지 절반의 중간 요소를 선택하고 2 단계에서와 같이 계속하여 나머지 배열의 반쪽을 제거하십시오. 결국 당신은 당신의 요소를 찾거나 볼 배열이 남아 있지 않습니다.

이진 검색은 배열 길이의 로그에 비례하여 시간으로 실행되므로 각 개별 요소를 보는 것보다 훨씬 빠를 수 있습니다.

] .has (obj)

가정합니다 .indexOf() 구현되었습니다

Object.defineProperty( Array.prototype,'has',
{
    value:function(o, flag){
    if (flag === undefined) {
        return this.indexOf(o) !== -1;
    } else {   // only for raw js object
        for(var v in this) {
            if( JSON.stringify(this[v]) === JSON.stringify(o)) return true;
        }
        return false;                       
    },
    // writable:false,
    // enumerable:false
})

!!!!!!!! 만들지 마십시오 Array.prototype.has=function(){... 모든 배열에 열거 가능한 요소를 추가하고 JS가 고장되기 때문입니다.

//use like          
[22 ,'a', {prop:'x'}].has(12) // false
["a","b"].has("a") //  true

[1,{a:1}].has({a:1},1) // true
[1,{a:1}].has({a:1}) // false

참조 대신 값별로 2 차 Arg (플래그) 힘 비교의 사용

원시 물체 비교

[o1].has(o2,true) // true if every level value is same

그것은 당신의 목적에 달려 있습니다. 웹을 위해 프로그램하는 경우 피하십시오 indexOf, 그것은 Internet Explorer 6 (여전히 많이 사용되는 것!)의 지원을받지 않거나 조건부 사용을 수행하지 않습니다.

if (yourArray.indexOf !== undefined) result = yourArray.indexOf(target);
else result = customSlowerSearch(yourArray, target);

indexOf 아마도 기본 코드로 코딩되므로 JavaScript에서 할 수있는 것보다 빠릅니다 (배열이 적절한 경우 이진 검색/이분법 제외). 참고 : 맛의 문제이지만 나는 return false; 당신의 일상이 끝나면 진정한 부울을 돌려주기 위해 ...

다음은 메타 지식이 있습니다. 배열로 무엇을 할 수 있는지 알고 싶다면 문서를 확인하십시오. 여기 모질라의 배열 페이지가 있습니다.

https://developer.mozilla.org/en-us/docs/javaScript/reference/global_objects/array

JavaScript 1.6에 추가 된 Indexof에 대한 참조가 표시됩니다.

객체가 JavaScript의 배열인지 확인하는 강력한 방법이 여기에 자세히 설명되어 있습니다.

다음은 다음과 같습니다 xa.js 내가 첨부하는 프레임 워크 utils = {} '컨테이너'. 이들은 배열을 올바르게 감지하는 데 도움이됩니다.

var utils = {};

/**
 * utils.isArray
 *
 * Best guess if object is an array.
 */
utils.isArray = function(obj) {
     // do an instanceof check first
     if (obj instanceof Array) {
         return true;
     }
     // then check for obvious falses
     if (typeof obj !== 'object') {
         return false;
     }
     if (utils.type(obj) === 'array') {
         return true;
     }
     return false;
 };

/**
 * utils.type
 *
 * Attempt to ascertain actual object type.
 */
utils.type = function(obj) {
    if (obj === null || typeof obj === 'undefined') {
        return String (obj);
    }
    return Object.prototype.toString.call(obj)
        .replace(/\[object ([a-zA-Z]+)\]/, '$1').toLowerCase();
};

그런 다음 객체가 배열에 있는지 확인하려면이 코드도 포함합니다.

/**
 * Adding hasOwnProperty method if needed.
 */
if (typeof Object.prototype.hasOwnProperty !== 'function') {
    Object.prototype.hasOwnProperty = function (prop) {
        var type = utils.type(this);
        type = type.charAt(0).toUpperCase() + type.substr(1);
        return this[prop] !== undefined
            && this[prop] !== window[type].prototype[prop];
    };
}

그리고 마지막 으로이 in_array 기능 :

function in_array (needle, haystack, strict) {
    var key;

    if (strict) {
        for (key in haystack) {
            if (!haystack.hasOwnProperty[key]) continue;

            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (!haystack.hasOwnProperty[key]) continue;

            if (haystack[key] == needle) {
                return true;
            }
        }
    }

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