Programing

자바 스크립트에서 [] .slice.call에 대한 설명은 무엇입니까?

lottogame 2020. 5. 18. 08:00
반응형

자바 스크립트에서 [] .slice.call에 대한 설명은 무엇입니까?


DOM NodeList를 일반 배열로 변환하기위한이 깔끔한 지름길을 우연히 발견했지만 작동 방식을 완전히 이해하지 못합니다.

[].slice.call(document.querySelectorAll('a'), 0)

따라서 빈 배열 []로 시작한 다음 slice결과를 call새 배열 로 변환하는 데 사용됩니다 .

내가 이해하지 못하는 것은 call입니다. document.querySelectorAll('a')NodeList에서 일반 배열 로 어떻게 변환 합니까?


여기서 일어나는 일은 slice()마치를 NodeList사용 하는 것처럼 호출한다는 것 call()입니다. 어떤 slice()이 경우에 수행하는 것은 현재 실행중인 개체 (지금은 원래 배열을 통해 다음 반복,를 빈 배열을 만들 것이다 NodeList) 결국 반환이 만든 빈 배열로 객체의 요소를 추가 유지. 여기에 대한 기사가 있습니다.

편집하다:

빈 배열로 시작합니다. [], 호출 결과를 새로운 배열로 변환하기 위해 slice가 사용됩니다.

그건 아니지. [].slice함수 객체를 반환합니다. 함수 객체에는 call()의 첫 번째 매개 변수를 할당 하는 함수 를 호출하는 함수 call()가 있습니다 this. 즉, 함수 가 배열이 아닌 매개 변수 (에서 NodeList반환 document.querySelectorAll('a')) 에서 호출되었다고 생각하게합니다 .


자바 스크립트에서 객체의 메소드는 런타임에 다른 객체에 바인딩 될 수 있습니다. 간단히 말해서, 자바 스크립트는 객체가 다른 객체의 메소드를 "빌리도록"허용합니다.

object1 = {
    name:'frank',
    greet:function(){
        alert('hello '+this.name)
    }
};

object2 = {
    name:'andy'
};

// Note that object2 has no greet method.
// But we may "borrow" from object1:

object1.greet.call(object2); // will show an alert with 'hello andy'

callapply이 작업을 수행 할 수 있습니다 함수 객체의 방법 (물론 자바 스크립트 기능의 객체이다). 따라서 코드에서 Nodelist가 배열의 슬라이스 메소드를 빌리고 있다고 말할 수 있습니다. 변환은 슬라이스가 다른 배열을 결과로 반환한다는 사실입니다.


에서 slice함수를 검색합니다 Array. 그런 다음 해당 함수를 호출하지만 결과를 실제 배열 대신 객체 document.querySelectorAll사용합니다 this.


배열과 유사한 객체를 실제 배열로 변환하는 기술입니다.

이러한 개체 중 일부는 다음과 같습니다.

  • arguments 기능에서
  • NodeList (가져온 후 내용이 변경 될 수 있음을 기억하십시오! 따라서 배열로 변환하면 고정 할 수 있습니다)
  • jQuery 컬렉션, 일명 jQuery 객체 (일부 문서 : API , type , learn )

예를 들어 객체는 참조로 전달되는 반면 배열은 값으로 전달되는 등 여러 가지 용도로 사용됩니다.

또한, 첫 번째 인수주의 0, omited 수 있습니다 여기에 철저한 설명 .

그리고 완전성을 위해 jQuery.makeArray ()도 있습니다.


어떻게 그 변환 document.querySelectorAll('a')A로부터 NodeList규칙적인 배열에?

이것은 우리가 가진 코드입니다.

[].slice.call(document.querySelectorAll('a'), 0)

먼저 해체하자

  []    // Array object
.slice // Accessing the function 'slice' present in the prototype of Array
.call // Accessing the function 'call' present in the prototype of function object(slice)
(document.querySelectorAll('a'),0) 
    // 'call' can have arguments like, (thisArg, arg1,arg2...n). 
   // So here we are passing the 'thisArg' as an array like object,
  // that is a 'nodeList'. It will be served as 'this' object inside of slice function.
 // And finally setting 'start' argument of slice as '0' and leaving the 'end' 
// argument as 'undefined'

1 단계 : call기능 실행

  • 내부 ( call) 이외 thisArg의 나머지 인수는 인수 목록에 추가됩니다.
  • 이제 함수 slice(객체에서 온 배열과 같은) this값을 인수 목록과 함께 바인딩하여 호출됩니다 . , 포함하는 인수thisArgdocument.querySelectorstart0

2 단계 : 2 slice내부에서 호출 된 함수 실행call

  • start변수에 다음 s과 같이 할당 됩니다0
  • 이후 end이다 undefined, this.length에 저장됩니다e
  • an empty array will be stored in a variable a
  • After making the above settings the following iteration will be happened

    while(s < e) {
      a.push(this[s]);
      s++;
    }
    
  • the filled up array a will be returned as the result.

P.S For better understanding of our scenario some steps that are necessary for our context has been ignored from the original algorithm of call and slice.


[].slice.call(document.querySelectorAll('.slide'));

1. The querySelectorAll() method returns all elements in the document that matches a specified selector(s). 

2. The call() method calls a function with a given this value and arguments provided individually.

3. The slice() method returns the selected elements in an array, as a new array object.

  so this line return the array of [object HTMLDivElement]. Here is the six div with classname "slide" so array length will be 6.

<div class="slideshow">

  <div class="slide">
    first slider1
  </div>
  <div class="slide">
    first slider2
  </div>
  <div class="slide">
    first slider3
  </div>
  <div class="slide">
    first slider4
  </div>
  <div class="slide">
    first slider5
  </div>
  <div class="slide">
    first slider6
  </div>

</div>

<script type="text/javascript">

  var arraylist = [].slice.call(document.querySelectorAll('.slide'));

  alert(arraylist);

</script>

From ES6: Simply make array with Array.from(element.children) or Array.from({length: 5})

참고URL : https://stackoverflow.com/questions/2125714/explanation-of-slice-call-in-javascript

반응형