Programing

배열의 마지막 항목 가져 오기

lottogame 2020. 9. 28. 07:51
반응형

배열의 마지막 항목 가져 오기


지금까지 내 JavaScript 코드는 다음과 같습니다.

var linkElement = document.getElementById("BackButton");
var loc_array = document.location.href.split('/');
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2]))); 
linkElement.appendChild(newT);

현재는 URL에서 배열의 두 번째 항목부터 마지막 ​​항목까지 가져옵니다. 그러나 배열의 마지막 항목이 "index.html"인지 확인하고, 그렇다면 마지막 항목에서 세 번째 항목을 대신 잡고 싶습니다.


if(loc_array[loc_array.length-1] == 'index.html'){
 //do something
}else{
 //something else.
}

서버가 "index.html"및 "inDEX.htML"에 대해 동일한 파일을 제공하는 경우 다음을 사용할 수도 있습니다 .toLowerCase()..

하지만 가능하다면이 서버 측 작업을 고려할 수 있습니다. JS가없는 사람들에게 더 깨끗하고 작동합니다.


단점이 있는지 확실하지 않지만 이것은 매우 간결 해 보입니다.

arr.slice(-1)[0] 

또는

arr.slice(-1).pop()

undefined배열이 비어 있으면 둘 다 반환 됩니다.


Array.pop 사용 :

var lastItem = anArray.pop();

중요 :이 마지막 요소를 반환 하고 제거 배열에서 그것을


@chaiguy가 게시 한 내용의 짧은 버전 :

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

-1 인덱스를 읽으면 undefined이미 반환 됩니다.

편집하다:

요즘 선호하는 것은 모듈을 사용하고 프로토 타입을 만지거나 전역 네임 스페이스를 사용하지 않는 것 같습니다.

export function last(array) {
    return array[array.length - 1];
}

두 가지 옵션은 다음과 같습니다.

var last = arr[arr.length - 1]

또는

var last = arr.slice(-1)[0]

전자가 더 빠르지 만 후자가 더 좋아 보입니다.

http://jsperf.com/slice-vs-length-1-arr


원래 ARRAY에 영향을주지 않고 가져 오는 방법은 다음과 같습니다.

a = [1,2,5,6,1,874,98,"abc"];
a.length; //returns 8 elements

pop ()을 사용하면 배열수정됩니다.

a.pop();  // will return "abc" AND REMOVES IT from the array 
a.length; // returns 7

그러나 이것을 사용할 수 있으므로 원래 배열에 영향미치지 않습니다 .

a.slice(-1).pop(); // will return "abc" won't do modify the array 
                   // because slice creates a new array object 
a.length;          // returns 8; no modification and you've got you last element 

"가장 깨끗한"ES6 방식 (IMO)은 다음과 같습니다.

const foo = [1,2,3,4];
const bar = [...foo].pop();

이것은 우리가 스프레드 연산자를 사용하지 않았다면했던 foo것처럼 mutating을 피 .pop()합니다.
즉, foo.slice(-1)[0]솔루션도 좋아 합니다.


array.pop()인덱스 보다는 사용하고 싶습니다 .

while(loc_array.pop()!= "index.html"){
}
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length])));

이렇게하면 항상 index.html 이전의 요소를 가져옵니다 (배열에 index.html이 하나의 항목으로 분리 된 경우). 참고 : 그래도 배열의 마지막 요소는 손실됩니다.


제거하지 않고 요소 만 얻으려면 다음을 사용하는 것이 더 간단하다고 생각합니다.

arr.slice(-1)[0]

참고 : 배열이 비어 있으면 (예 :) []이 반환 undefined됩니다.

그건 그렇고 ... 나는 성능을 확인하지 않았지만 쓰기가 더 간단하고 깔끔하다고 생각합니다.


배열의 마지막 항목을 가져 오는 것은 음수 값으로 slice 메소드를 사용하여 얻을 수 있습니다 .

여기 하단에서 자세한 내용을 읽을 수 있습니다 .

var fileName = loc_array.slice(-1)[0];
if(fileName.toLowerCase() == "index.html")
{
  //your code...
}

pop ()을 사용하면 배열이 변경되지만 항상 좋은 생각은 아닙니다.


이 패턴을 사용할 수 있습니다 ...

let [last] = arr.slice(-1);

읽기는 좋지만 새로운 어레이를 생성하므로 다른 솔루션보다 효율성이 떨어지지 만 애플리케이션 성능 병목 현상 이 거의 발생하지 않습니다 .


한 번에 마지막 요소를 얻으려면 다음을 사용할 수 있습니다 Array#splice().

lastElement = document.location.href.split('/').splice(-1,1);

여기서는 분할 된 요소를 배열에 저장 한 다음 마지막 요소에 도달 할 필요가 없습니다. 마지막 요소를 얻는 것이 유일한 목적이라면 이것을 사용해야합니다.

참고 : 마지막 요소를 제거 하여 원래 배열변경합니다 . 마지막 요소를 팝 splice(-1,1)하는 pop()함수 생각하십시오 .


Array 프로토 타입을 오버로드하는 것을 두려워하지 않는 사람들을 위해 (그리고 열거 형 마스킹 을 사용해서는 안됩니다) :

Object.defineProperty( Array.prototype, "getLast", {
    enumerable: false,
    configurable: false,
    writable: false,
    value: function() {
        return this[ this.length - 1 ];
    }
} );

jQuery 는 이것을 깔끔하게 해결합니다.

> $([1,2,3]).get(-1)
3
> $([]).get(-1)
undefined

나는 일반적으로 underscorejs를 사용 합니다 .

if (_.last(loc_array) === 'index.html'){
  etc...
}

나를 위해 그것은 더 의미 론적입니다 loc_array.slice(-1)[0]


이 질문은 오래 전부터 있었기 때문에 아무도 마지막 요소를 pop().

arr.pop()과 똑같이 효율적 arr[arr.length-1]이며 둘 다과 같은 속도 arr.push()입니다.

따라서 다음과 같이 벗어날 수 있습니다.

[체크 --- EDITED thePop없는 undefined추진 전에] ---

let thePop = arr.pop()
thePop && arr.push(thePop)

--- 편집 종료 ---

이것으로 줄일 수 있습니다 (동일한 속도 [편집 :하지만 안전하지 않습니다!]) :

arr.push(thePop = arr.pop())    //Unsafe if arr empty

이것은.보다 두 배 느리지 arr[arr.length-1]만 인덱스를 다룰 필요가 없습니다. 그것은 언제든지 금의 가치가 있습니다.

내가 시도한 솔루션 중 실행 시간 단위 (ETU)의 배수 arr[arr.length-1]:

[방법] .............. [ETU 5 개 요소] ... [ETU 1 백만 요소]

arr[arr.length - 1]      ------> 1              -----> 1

let myPop = arr.pop()
arr.push(myPop)          ------> 2              -----> 2

arr.slice(-1).pop()      ------> 36             -----> 924  

arr.slice(-1)[0]         ------> 36             -----> 924  

[...arr].pop()           ------> 120            -----> ~21,000,000 :)

마지막 세 가지 옵션 인 특히 [...arr].pop()는 배열의 크기가 증가함에 따라 훨씬 더 나빠집니다. 내 컴퓨터의 메모리 제한이없는 컴퓨터에서는 [...arr].pop()아마도 120 : 1 비율처럼 유지됩니다. 그래도 아무도 자원 돼지를 좋아하지 않습니다.


const [lastItem] = array.slice(-1);

-1이있는 Array.prototype.slice 는 원래 배열의 마지막 항목 만 포함하는 새 배열을 만드는 데 사용할 수 있습니다. 그런 다음 Destructuring Assignment 를 사용하여 새 배열의 첫 번째 항목을 사용하여 변수를 만들 수 있습니다 .

const lotteryNumbers = [12, 16, 4, 33, 41, 22];
const [lastNumber] = lotteryNumbers.slice(-1);

console.log(lotteryNumbers.slice(-1));
// => [22]
console.log(lastNumber);
// => 22


const lastElement = myArray[myArray.length - 1];

성능 관점에서 볼 때 가장 좋은 옵션입니다 (arr.slice (-1)보다 약 1000 배 빠름).


개인적으로 나는 kuporific / kritzikratzi의 답변을 찬성 할 것입니다. 중첩 된 배열로 작업하는 경우 array [array.length-1] 메서드는 매우 추악합니다.

var array = [[1,2,3], [4,5,6], [7,8,9]]
array.slice(-1)[0]
//instead of 
array[array.length-1]
//Much easier to read with nested arrays
array.slice(-1)[0].slice(-1)[0]
//instead of
array[array.length-1][array[array.length-1].length-1]

You can add a last() function to the Array prototype.

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

In ECMAScript proposal Stage 1 there is a suggestion to add an array property that will return the last element: proposal-array-last.

Syntax:

arr.lastItem // get last item
arr.lastItem = 'value' // set last item

arr.lastIndex // get last index

You can use polyfill.

Proposal author: Keith Cirkel(chai autor)


You could add a new property getter to the prototype of Array so that it is accessible through all instances of Array.

Getters allow you to access the return value of a function just as if it were the value of a property. The return value of the function of course is the last value of the array (this[this.length - 1]).

Finally you wrap it in a condition that checks whether the last-property is still undefined (not defined by another script that might rely on it).

if(typeof Array.prototype.last === 'undefined') {
    Object.defineProperty(Array.prototype, 'last', {
        get : function() {
            return this[this.length - 1];
        }
    });
}

// Now you can access it like
[1, 2, 3].last;            // => 3
// or
var test = [50, 1000];
alert(test.last);          // Says '1000'

Does not work in IE ≤ 8.


EDITED:

Recently I came up with one more solution which I now think is the best for my needs:

function w(anArray) {
  return {
    last() {
      return anArray [anArray.length - 1];
    };
  };
}

With the above definition in effect I can now say:

let last = w ([1,2,3]).last();
console.log(last) ; // -> 3

The name "w" stands for "wrapper". You can see how you could easily add more methods besides 'last()' to this wrapper.

I say "best for my needs", because this allows me to easily add other such "helper methods" to any JavaScript built-in type. What comes to mind are the car() and cdr() of Lisp for instance.


Here's more Javascript art if you came here looking for it

In the spirit of another answer that used reduceRight(), but shorter:

[3, 2, 1, 5].reduceRight(a => a);

It relies on the fact that, in case you don't provide an initial value, the very last element is selected as the initial one (check the docs here). Since the callback just keeps returning the initial value, the last element will be the one being returned in the end.

Beware that this should be considered Javascript art and is by no means the way I would recommend doing it, mostly because it runs in O(n) time, but also because it hurts readability.

And now the serious answer

The best way I see (considering you want it more concise than array[array.length - 1]) is this:

const last = a => a[a.length - 1];

Then just use the function:

last([3, 2, 1, 5])

The function is actually useful in case you're dealing with an anonymous array like [3, 2, 1, 5] used above, otherwise you'd have to instantiate it twice, which would be inefficient and ugly:

[3, 2, 1, 5][[3, 2, 1, 5].length - 1]

Ugh.

For instance, here's a situation where you have an anonymous array and you'd have to define a variable, but you can use last() instead:

last("1.2.3".split("."));

To prevent removing last item from origin array you could use

Array.from(myArray).pop()

Mostly supported of all browsers (ES6)


Whatever you do don't just use reverse() !!!

A few answers mention reverse but don't mention the fact that reverse modifies the original array, and doesn't (as in some other language or frameworks) return a copy.

var animals = ['dog', 'cat'];

animals.reverse()[0]
"cat"

animals.reverse()[0]
"dog"

animals.reverse()[1]
"dog"

animals.reverse()[1]
"cat"

This can be the worst type of code to debug!


I'll suggest to create helper function and reuse it every time, you'll need it. Lets make function more general to be able to get not only last item, but also second from the last and so on.

function last(arr, i) {
    var i = i || 0;
    return arr[arr.length - (1 + i)];
}

Usage is simple

var arr = [1,2,3,4,5];
last(arr);    //5
last(arr, 1); //4
last(arr, 9); //undefined

Now, lets solve the original issue

Grab second to last item form array. If the last item in the loc_array is "index.html" grab the third to last item instead.

Next line does the job

last(loc_array, last(loc_array) === 'index.html' ? 2 : 1);

So, you'll need to rewrite

var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2]))); 

in this way

var newT = document.createTextNode(unescape(capWords(last(loc_array, last(loc_array) === 'index.html' ? 2 : 1)))); 

or use additional variable to increase readability

var nodeName = last(loc_array, last(loc_array) === 'index.html' ? 2 : 1);
var newT = document.createTextNode(unescape(capWords(nodeName)));

I think the easiest and super inefficient way is:

var array = ['fenerbahce','arsenal','milan'];
var reversed_array = array.reverse(); //inverts array [milan,arsenal,fenerbahce]
console.log(reversed_array[0]) // result is "milan".

How about something like below:

if ('index.html' === array[array.length - 1]) {  
   //do this 
} else { 
   //do that 
}

If using Underscore or Lodash, you can use _.last(), so something like:

if ('index.html' === _.last(array)) {  
   //do this 
} else { 
   //do that 
}

Or you can create your own last function:

const _last = arr => arr[arr.length - 1];

and use it like:

if ('index.html' === _last(array)) {  
   //do this 
} else { 
   //do that 
}

Using ES6/ES2015 spread operator (...) you can do the following way.

const data = [1, 2, 3, 4]
const [last] = [...data].reverse()
console.log(last)

Please notice that using spread operator and reverse we did not mutated original array, this is a pure way of getting a last element of the array.

참고URL : https://stackoverflow.com/questions/3216013/get-the-last-item-in-an-array

반응형