2009-09-22 10 views

답변

2

: 이전 버전의

var index = arr.indexOf('hello'); 

를 그냥 배열 자신을 통해 루프 것이다 .

흥미롭게도, 크롬 alert([].indexOf) 당신에게 구현을 제공합니다

function indexOf(element, index) { 
    var length = this.length; 
    if (index == null) { 
    index = 0; 
    } else { 
    index = (_IsSmi(IS_VAR(index)) ? index : ToInteger(index)); 
    if (index < 0) index = length + index; 
    if (index < 0) index = 0; 
    } 
    for (var i = index; i < length; i++) { 
    var current = this[i]; 
    if (!(typeof(current) === 'undefined') || i in this) { 
     if (current === element) return i; 
    } 
    } 
    return -1; 
} 

가 IE에서 작동하는 경우

+0

어디에서 자바 스크립트 버전을 볼 수 있습니까? – omg

+0

할 수있는 가장 좋은 방법은 지원되는지 확인하는 것입니다. if (typeof [] .indexOf == 'undefined') {당신은 가지고 있지 않습니다} – Greg

+0

지원되지만 아직 자바 스크립트 버전을 모르겠습니다. ( – omg

3
arr.indexOf("hello"); 

indexOf 방법은 (는 자바 스크립트 1.6에서 추가되었다), 그러나 당신이 그것을합니다 (MDC page for indexOf의 코드) 그렇지 않은에서 작동하도록하려면 다음 코드를 사용할 수있는 모든 브라우저에서 지원되지 않습니다 : 당신이 .indexOf() 사용할 수 있습니다 1.6 자바 스크립트에서

if (!Array.prototype.indexOf) 
{ 
    Array.prototype.indexOf = function(elt /*, from*/) 
    { 
    var len = this.length >>> 0; 

    var from = Number(arguments[1]) || 0; 
    from = (from < 0) 
     ? Math.ceil(from) 
     : Math.floor(from); 
    if (from < 0) 
     from += len; 

    for (; from < len; from++) 
    { 
     if (from in this && 
      this[from] === elt) 
     return from; 
    } 
    return -1; 
    }; 
} 
0
arr.indexOf('hello');

몰라요 ... _IsSmi(IS_VAR(index)) 비록 무엇을 묻지 않음 하지만 (그것은 분명히 Firefox와 Webkit에서 작동합니다).

:-D

+0

정말 투표지를 내려야하는 이유는 모르겠지만 .... 대답은 다른 것과 크게 다르지 않습니다 (틀린 것은 아닙니다) ??? – NawaMan