在Javascript中引用数组的最后一个元素?

nfp*_*zyf 1 javascript

在我的代码中,我有很多这样的代码:

my_array[my_array.length - 1] = sth;
Run Code Online (Sandbox Code Playgroud)

是否可以定义一个简单的变量来指向数组的最后一个元素?像这样:

var ref =  (&|*, sth like that) my_array[my_array.length - 1];
ref = sth;
Run Code Online (Sandbox Code Playgroud)

Kar*_*rol 5

您将不得不更改数组原型,并使用如下所示:

var arr = ['a','b','c'];

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

arr.last();
Run Code Online (Sandbox Code Playgroud)

Shuold工作 - 您可以在Chrome JS控制台中查看它.