Development Tip

프로토 타입 array.last ()에 해당하는 jQuery

yourdevel 2020. 11. 25. 21:16
반응형

프로토 타입 array.last ()에 해당하는 jQuery


원기:

var array = [1,2,3,4];
var lastEl = array.last();

jQuery에서 이와 비슷한 것이 있습니까?


간단한 자바 스크립트를 사용하지 않는 이유는 무엇입니까?

var array=[1,2,3,4];
var lastEl = array[array.length-1];

원하는 경우 메소드로도 작성할 수 있습니다 (프로토 타입이 페이지에 포함되지 않았다고 가정).

Array.prototype.last = function() {return this[this.length-1];}

slice () 사용 :

var a = [1,2,3,4];
var lastEl = a.slice(-1)[0]; // 4
// a is still [1,2,3,4]

pop ();

var a = [1,2,3,4];
var lastEl = a.pop(); // 4
// a is now [1,2,3]

자세한 내용 https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array 를 참조하십시오.


jQuery 객체를 다룰 때 .last(), 일치하는 요소를 세트의 마지막 요소로만 필터링합니다.

물론 jQuery로 네이티브 배열을 래핑하여 다음과 같이 할 수 있습니다.

var a = [1,2,3,4];
var lastEl = $(a).last()[0];

get 함수를 사용하지 않는 이유는 무엇입니까?

var a = [1,2,3,4];
var last = $(a).get(-1);

http://api.jquery.com/get/ 추가 정보

편집 : DelightedD0D가 지적했듯이 이것은 jQuery의 문서에 따라 사용할 올바른 기능이 아니지만 여전히 올바른 결과를 제공합니다. 코드를 올바르게 유지하려면 Salty의 답변을 사용하는 것이 좋습니다.


다음과 같은 배열에서 프로토 타입을 사용하는 경우 :

Array.prototype.last = function() {return this[this.length-1];}

forloops를 사용하면 이렇게됩니다.

var a = [0,1,2];
out --> 0
out --> 1
out --> 2
out --> last

나는 이미 답이 주어진 것을 알고 있지만 이것에 대한 또 다른 해결책이 있다고 생각합니다. 배열을 가져 와서 뒤집고 다음과 같이 첫 번째 배열 항목을 출력 할 수 있습니다.

var a = [1,2,3,4];
var lastItem = a.reverse () [0];

나를 위해 잘 작동합니다.


배열의 경우 다음을 사용하여 마지막 요소 위치를 검색 할 수 있습니다 array.length - 1.

var a = [1,2,3,4];

var lastEl = a[a.length-1]; // 4

jQuery에는 : last 선택기가 있지만 일반 배열에서는 도움이되지 않습니다.


에 따르면 jsPerf : 마지막 항목 방법은 , 가장 성능이 좋은 방법이다 array[array.length-1]. 그래프는 작업 당 시간이 아니라 초당 작업을 표시합니다.

개발자가 단일 작업의 성능이 중요하다고 생각하는 것은 일반적이지만 잘못되었습니다. 그렇지 않습니다. 성능은 동일한 작업을 많이 수행 할 때만 중요합니다. 이 경우 정적 값 ( length)을 사용하여 특정 인덱스 ( length-1) 에 액세스하는 것이 가장 빠르고 가깝지도 않습니다.


다음 테스트 사례를 참조하십시오. http://jsperf.com/last-item-method 가장 효과적인 방법은 .pop 메서드 (V8)를 사용하는 것이지만 배열의 마지막 요소가 손실됩니다.


SugarJS

jQuery는 아니지만 jQuery 외에 유용 할 수있는 다른 라이브러리 : Try SugarJS .

Sugar is a Javascript library that extends native objects with helpful methods. It is designed to be intuitive, unobtrusive, and let you do more with less code.

With SugarJS, you can do:

[1,2,3,4].last()    //  => 4

That means, your example does work out of the box:

var array = [1,2,3,4];
var lastEl = array.last();    //  => 4

More Info


url : www.mydomain.com/user1/1234

$.params = window.location.href.split("/"); $.params[$.params.length-1];

You can split based on your query string separator


I use this:

array.reverse()[0]

You reverse the array with reverse() and then pick the first item of the reversed version with [0], that is the last one of the original array.

You can use this code if you don't care that the array gets reversed of course, because it will remain so.

참고URL : https://stackoverflow.com/questions/1159978/jquery-equivalent-to-prototype-array-last

반응형