Javascript 获取数组中的最后一项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3216013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:42:45  来源:igfitidea点击:

Get the last item in an array

javascriptarrays

提问by balexander

Here is my JavaScript code so far:

到目前为止,这是我的 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);

Currently it takes the second to last item in the array from the URL. However, I want to do a check for the last item in the array to be "index.html"and if so, grab the third to last item instead.

目前它从 URL 中获取数组中倒数第二个项目。但是,我想检查数组中的最后一项"index.html",如果是,则改为获取倒数第三项。

回答by Aaron Harun

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

In the event that your server serves the same file for "index.html" and "inDEX.htML" you can also use: .toLowerCase().

如果您的服务器为“index.html”和“inDEX.htML”提供相同的文件,您还可以使用:.toLowerCase()

Though, you might want to consider doing this server-side if possible: it will be cleaner and work for people without JS.

不过,如果可能,您可能想考虑在服务器端执行此操作:它会更干净,并且适用于没有 JS 的人。

回答by kritzikratzi

Not sure if there's a drawback, but this seems quite concise:

不确定是否有缺点,但这似乎很简洁:

arr.slice(-1)[0] 

or

或者

arr.slice(-1).pop()

Both will return undefinedif the array is empty.

undefined如果数组为空,两者都将返回。

回答by mohawke

Use Array.pop:

使用Array.pop

var lastItem = anArray.pop();

Important: This returns the last element andremovesit from the array

重要提示:这将返回最后一个元素并将其从数组中删除

回答by Aram Kocharyan

A shorter version of what @chaiguy posted:

@chaiguy 发布内容的简短版本:

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

Reading the -1 index returns undefinedalready.

读取 -1 索引undefined已经返回。

EDIT:

编辑:

These days the preference seems to be using modules and to avoid touching the prototype or using a global namespace.

如今,偏好似乎是使用模块并避免接触原型或使用全局命名空间。

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

回答by Josh Click

Two options are:

两个选项是:

var last = arr[arr.length - 1]

or

或者

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

The former is faster, but the latter looks nicer

前者更快,但后者看起来更好

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

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

回答by ucefkh

Here's how to get it with no effect on the original ARRAY

这是在不影响原始数组的情况下获得它的方法

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

If you use pop(), it will modify your array

如果您使用 pop(),它将修改您的数组

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

But you can use this so it has no effecton the original array:

但是您可以使用它,因此它对原始数组没有影响

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 

回答by ddd

The "cleanest" ES6 way (IMO) would be:

“最干净”的 ES6 方式(IMO)是:

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

This avoids mutating foo, as .pop()would had, if we didn't used the spread operator.
That said, I like aswell the foo.slice(-1)[0]solution.

如果我们不使用扩展运算符foo,这.pop()将避免 mutating 。
也就是说,我也喜欢这个foo.slice(-1)[0]解决方案。

回答by Pablo Mescher

I'd rather use array.pop()than indexes.

我宁愿使用而array.pop()不是索引。

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

this way you always get the element previous to index.html (providing your array has isolated index.html as one item). Note:You'll lose the last elements from the array, though.

通过这种方式,您始终可以获取 index.html 之前的元素(前提是您的数组已将 index.html 作为一项隔离)。注意:不过,您将丢失数组中的最后一个元素。

回答by terribleWeb

I think if you only want get the element without remove, is more simple use this:

我认为如果你只想在不删除的情况下获取元素,使用这个更简单:

arr.slice(-1)[0]

Note: If the array is empty (eg. []) this will return undefined.

注意:如果数组为空(例如[]),这将返回undefined.

by the way... i didnt check performance, but i think is more simple and clean to write

顺便说一句......我没有检查性能,但我认为写起来更简单和干净

回答by Jamie Mason

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

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

Array.prototype.slicewith -1 can be used to create a new Array containing only the last item of the original Array, you can then use Destructuring Assignmentto create a variable using the first item of that new Array.

带有 -1 的Array.prototype.slice可用于创建仅包含原始 Array 的最后一项的新 Array,然后您可以使用Destructuring Assignment使用该新 Array 的第一项创建变量。

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

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