1

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;
3
  • is your goal to replace the last element of an array? Commented Mar 28, 2013 at 2:11
  • Yes, a lot of repeated my_array[my_array.length - 1], kind of noising Commented Mar 28, 2013 at 2:12
  • 1
    splice() work for you?, with a negative index i.e. my_array.splice(-1,1,sth) Commented Mar 28, 2013 at 2:14

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah - I think it's best way to achieve this goal.
Another fun trick would be to use 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.