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.
var ref = Array.prototype.last.bind(arr), to bind the function to an instance, so you don't have to pass around the array, just a bound function that returns the last item of desired array.
my_array[my_array.length - 1], kind of noising