2013-04-29 2 views
2

내가 "중간 정도 괜찮은"자바 프로그래머라고 언급 할 가치는있다.하지만 실제로 자바 스크립트를 배운다는 생각은 내가 쓰는 것을 본 적이있는 독창적 인 물건처럼 잘 발굴된다. 난 그냥 비 OOP PHP 프로그래머이며 JS 완전히 새로운 세계처럼 보인다. fisheye navigationArray.prototype -이 기능이 무엇인지 확실하지 않습니다! (Q1)

[].indexOf||(Array.prototype.indexOf=function(v,n){ 
     n=(n==null)?0:n;var m=this.length; 
     for(var i=n;i<m;i++)if(this[i]==v)return i; 
     return-1; 
}); 

솔직히 나는 심지어 변수에 값을 할당 볼 수 없습니다 :이 스크립트에있는 코드 블록이

! 그것은 작가가 indexOf 메서드에 대한 냄새를 맡고있는 것 같지만 그것은 이해가되지 않습니다 ..

나는이 코드 절을 (실제로 잘 쓰여질 것으로 보이는) 섹션으로 해부한다면 나는 내 길을 갈 것입니다. 더 깊은 자바 스크립트 개념에 중점을 둡니다. 감사!

+1

그것은라는 함수를 만듭니다 'Array' 내부에 "indexOf"가 존재하지 않으면이를 나타냅니다. – TheBronx

+2

'... indexOf = function ...'- 하나의'= ', 하나의 할당. – Quentin

답변

2

indexOf() 메서드는 Internet Explorer 8 및 보다 이전에 지원되지 않습니다. http://www.w3schools.com/jsref/jsref_indexof_array.asp

작성자는 indexOf 메소드가 없으면 또 다른 구현을 수행합니다.

+1

w3schools는 끔찍한 리소스입니다. 나는 이것을 제안한다 : https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf –

+0

developer.mozilla.org는 정말 대단하다. 왜 w3schools가 끔찍하다고 생각하니? –

+0

http://w3fools.com을 읽어보십시오. w3schools에는 많은 잘못된 정보가 포함되어 있으며 더 많은 정보가 계속 표시됩니다. –

2

이 값은 Array.prototype.indexOf 메서드 (https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf)의 polyfill입니다. 여기에 대한 지원 테이블을 볼 수 있습니다 : http://kangax.github.io/es5-compat-table/#Array.prototype.indexOf

배열 리터럴에서 메소드를 확인하여이 코드가 수행하는 내용은 Array.prototype.indexOf가 있는지 확인하십시오. 그렇지 않으면 Array.prototype.indexOf에 함수를 할당합니다. 기본적으로 누락 된 기능을 채 웁니다.

0

에서 설명

// v is the element you are checking for in the array and n is the index from which the check starts 
Array.prototype.indexOf = function(v,n) { 

    // check if the "fromIndex" n has been specified, if not start the check from the first element 
    n= (n==null) ? 0 : n; 
    // m stores the length of the array in which the check is being performed 
    var m=this.length; 
    // using the for loop to iterate each element of the array 
    for(var i=n;i<m;i++) 
     if(this[i]==v) // checking if the array element (this refers to the array) is the same as the supplied value, if so it returns the index of the element which matches the supplied value 
      return i; 
    // If supplied value is not found in the array, the return value is -1 
    return-1; 
}); 

Array 객체의 프로토 타입에 다음과 같은 기능을 할당합니다

//find out if indexOf exists if not add function to prototype 
    [].indexOf||(Array.prototype.indexOf=function(v,n){ 

      //start search at n which is passed in, if n is not passed in start at 0 
      n=(n==null)?0:n; 

      // get length of array 
      var m=this.length; 

      for(var i=n;i<m;i++) 
      { 
       //if you find the value return it 
       if(this[i]==v)return i; 
      } 

      //if value wasnt found return -1 
      return-1; 
     }); 
+0

JS에서는 [null-coalescing operator] (http://stackoverflow.com/q/476436/1048572)가 아니라 단순한 'OR'이고 'indexOf' 속성은'null '을 반환하지 않습니다. – Bergi

관련 문제