JavaScriptArray 类没有提供最后一个方法来检索数组的最后一个元素,这有点奇怪。我知道解决方案很简单(AR [ Ar.length-1]) ,但是,这种方法使用得太频繁了。
有没有什么重要的原因,为什么这还没有被纳入?
It's easy to define one yourself. That's the power of JavaScript.
if(!Array.prototype.last) { Array.prototype.last = function() { return this[this.length - 1]; } } var arr = [1, 2, 5]; arr.last(); // 5
但是,这可能会导致第三方代码出现问题,因为第三方代码(不正确地)使用 for..in循环迭代数组。
for..in
但是,如果您没有与 browser support问题绑定,那么使用新的 ES5语法到 定义属性就可以解决这个问题,方法是使函数不可枚举,如下所示:
Object.defineProperty(Array.prototype, 'last', { enumerable: false, configurable: true, get: function() { return this[this.length - 1]; }, set: undefined }); var arr = [1, 2, 5]; arr.last; // 5
因为 Javascript 的变化非常缓慢,这是因为人们升级浏览器的速度很慢。
许多 Javascript 库实现了它们自己的 last()函数!
last()
Array.prototype.last = Array.prototype.last || function() { var l = this.length; return this[l-1]; } x = [1,2]; alert( x.last() )
你可以这样做:
[10, 20, 30, 40].slice(-1)[0]
console.log([10, 20, 30, 40].slice(-1)[0])
The amount of helper methods that can be added to a language is infinite. I suppose they just haven't considered adding this one.
我来这里寻找这个问题的答案。切片的答案可能是最好的,但是我继续创建了一个“ last”函数,只是为了练习扩展原型,所以我想我应该继续并分享它。与其他方法相比,它还有一个额外的好处,那就是允许您可选地通过数组向后计数,然后拉出,比如倒数第二个或倒数第三个项目。如果你没有指定一个计数,它只是默认为1,并拉出最后一个项目。
Array.prototype.last = Array.prototype.last || function(count) { count = count || 1; var length = this.length; if (count <= length) { return this[length - count]; } else { return null; } }; var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; arr.last(); // returns 9 arr.last(4); // returns 6 arr.last(9); // returns 1 arr.last(10); // returns null
i = [].concat(loves).pop(); //corn
偶像猫喜欢爆米花
这里有另一种更简单的方法来切割最后一个元素
var tags = [1, 2, 3, "foo", "bar", "foobar", "barfoo"]; var lastObj = tags.slice(-1);
lastObj is now ["barfoo"].
lastObj
["barfoo"]
Python does this the same way and when I tried using JS it worked out. I am guessing string manipulation in scripting languages work the same way.
Similarly, if you want the last two objects in a array,
var lastTwoObj = tags.slice(-2)
会给你 ["foobar", "barfoo"]等等。
["foobar", "barfoo"]
另一个选择,特别是如果您已经在使用 UnderscoreJS,那么应该是:
_.last([1, 2, 3, 4]); // Will return 4
方法将弹出最后一个值。但问题是您将丢失数组中的最后一个值
是啊,或者只是:
var arr = [1, 2, 5]; arr.reverse()[0]
如果您想要的值,而不是一个新的列表。