Javascript 获取数组的倒数第二个项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6499012/
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 22:03:06  来源:igfitidea点击:

get the second to last item of an array?

javascriptjqueryarrays

提问by laukok

How can I get the last second item in an array?

如何获取数组中的最后一个第二项?

For instance,

例如,

var fragment = '/news/article-1/'
var array_fragment = fragment.split('/');
var pg_url = $(array_fragment).last()[0];

This returns an empty value. But I want to get article-1

这将返回一个空值。但我想得到article-1

Thanks.

谢谢。

回答by Pablo Fernandez

Not everything has to be done using jQuery.

并非所有事情都必须使用 jQuery 来完成。

In plain old javascript you can do:

在普通的旧 javascript 中,您可以执行以下操作:

var pg_url = array_fragment[array_fragment.length - 2]

Easier and faster :)

更简单更快:)

回答by JJ Geewax

Looks like you can also use Javascript's slicemethod:

看起来你也可以使用 Javascript 的slice方法:

var path = 'a/b/c/d';
path.split('/').slice(-2, -1)[0]; // c

You can also think of "second to last element in the array" as "second element of the array reversed":

您还可以将“数组中的倒数第二个元素”视为“数组的第二个元素反转”:

var path = 'a/b/c/d';
path.split('/').reverse()[1]; // c

回答by 151291

Step 1: Use split()Method to split the elements into an array.

第一步:使用split()方法将元素拆分成一个数组。

var fragment_arr = fragment.split("/");

Step 2: Use slice(-2)Method to select last 2 element from array, the negative number to select from the end of an array.

步骤2:使用slice(-2)方法从数组中选择最后2个元素,从数组末尾选择负数。

var lastTwo = fragment_arr.slice(-2);

Step 3: lastTwoarray contains last two elements of fragment_arr, now you can access like this

第 3 步:lastTwo数组包含 的最后两个元素fragment_arr,现在您可以像这样访问

var element = lastTwo[0];
alert(element);

Short answer: you can combine step 2 and 3 like below

简短回答:您可以像下面一样结合第 2 步和第 3 步

var element = fragment_arr.slice(-2)[0];
alert(element);

回答by Penny Liu

This can be covered by lodash _.nth:

这可以被 lodash 覆盖_.nth

var fragment = '/news/article-1/'
var array_fragment = _.split(fragment, '/');
var second_last = _.nth(array_fragment, -2);
console.log(second_last);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

回答by dave

var pg_url = array_fragment[array_fragment.length -2]

array_fragment isn't a jquery variable, it's a plain old javascript variable so no need for $()

array_fragment 不是 jquery 变量,它是一个普通的旧 javascript 变量,因此不需要 $()

回答by Travis J

If accessing arrays in reverse is something that is going to be often required, and not just the second to last index, a simple expansion to the prototype could be used.

如果反向访问数组是经常需要的,而不仅仅是倒数第二个索引,则可以使用对原型的简单扩展。

When extending something as large and used as the Array prototype ensure that you are not going to affect any other part of its use. This is done by making sure that the property is not enumerable so that for inwill not choke anywhere else (some people and libraries use for into iterate arrays).

当扩展与 Array 原型一样大和使用的东西时,请确保您不会影响其使用的任何其他部分。这是通过确保该属性不可枚举来完成的,这样for in就不会在其他任何地方阻塞(某些人和库用于for in迭代数组)。

Object.defineProperty(Array.prototype, 'rev', {
  enumerable: false,
  value: function(index){
    return this[this.length - 1 - index];
  }
});

document.write([1,2,3,4,5,6].rev(1));

And now you can use zero based indexing in reverse.

现在您可以反向使用基于零的索引。

回答by Jason Turnage

This question is old but still relevant. Slice with length-1 is the best bet, but as an alternative with underscore/lodash:

这个问题很老,但仍然相关。长度为 1 的切片是最好的选择,但作为下划线/lodash 的替代方案:

_.initial() gets all but the last

_.initial() 获取除最后一个之外的所有内容

_.last() gets the last

_.last() 得到最后一个

So you could do

所以你可以这样做

_.last(_.initial([1,2,3,4])) 

or chained:

或链接:

_.chain([1,2,3,4])
 .initial()
 .last()
 .value();

which gives you back 3.

这给你回 3。

Or in the original question:

或者在原始问题中:

var fragment = '/news/article-1/'
var array_fragment = fragment.split('/');
var pg_url = _.chain(array_fragment).initial().last().value();

回答by mbunch

The following works for a string with nth 'url' parts.

以下适用于具有第 n 个“url”部分的字符串。

var fragment = '/t/e/s/t/i/n/g/';
var fragment = '/t/';

If the fragment is of variable length, you need a solution that works for various fragment sizes.

如果片段长度可变,您需要一个适用于各种片段大小的解决方案。

var fragment = '/news/article-1/';
var array_fragment = fragment.split('/');

Splitseparates the fragment string where it finds '/'s. Split takes the value before and after the split character. In this case there is nothing before the first slash or after the last slash. The empty values are added to the array_fragment in the first and last array positions.

Split在它找到 '/' 的地方分隔片段字符串。拆分采用拆分字符前后的值。在这种情况下,第一个斜线之前或最后一个斜线之后没有任何内容。空值被添加到 array_fragment 的第一个和最后一个数组位置。

jQuery
var pg_url = $(array_fragment)[$(array_fragment).length - 2];

javascript
var pg_url = array_fragment[array_fragment.length - 2];

As you can see, jQuery is not needed for this solution.

如您所见,此解决方案不需要 jQuery。

Array_fragment.length - 2is counting the length of the array_fragment, and selecting the second item from the end. The last value is "" due to Split('/') adding an empty value to the end of the array_fragment array.

Array_fragment.length - 2正在计算array_fragment的长度,并选择从末尾开始的第二项。由于 Split('/') 在 array_fragment 数组的末尾添加了一个空值,所以最后一个值为 ""。

Simplified and all put together:

简化并放在一起:

var f = '/t/e/s/t/i/n/g/'.split('/');
f[f.length - 2]

回答by Uliana Pavelko

const myArray: Array<string> = ['first', 'second', 'third'];

Split myArray by second last item.

按倒数第二个项目拆分 myArray。

const twoItemsFromEnd = myArray.slice(-2); //Outputs: ['second', 'third']

Then

然后

const secondLast = twoItemsFromEnd[0];

Or:

或者:

const secondLast = (params.slice(-2))[0];

回答by Ipsita Mallick

var a = [1,2,3,4];
var b = a.slice(-2,-1);
console.log(b);

The answer is [3].You just have to mention the start and end for slice.

答案是[3]。你只需要提到切片的开始和结束。