[英]Reference last element of an array in Javascript?
In my code, I have a lot code like this: 在我的代码中,我有很多这样的代码:
my_array[my_array.length - 1] = sth;
Is it possible to define a simple variable to point to last element of array?like this: 是否可以定义一个简单的变量来指向数组的最后一个元素?
var ref = (&|*, sth like that) my_array[my_array.length - 1];
ref = sth;
You will have to change array prototype, and use it like below: 您将不得不更改数组原型,并按如下方式使用它:
var arr = ['a','b','c'];
Array.prototype.last=function() {
if(this.length >= 1) {
return this[this.length - 1];
}
else {
return null;
}
};
arr.last();
Shuold work - you can check it in Chrome JS console. Shuold的工作-您可以在Chrome JS控制台中进行检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.