0

I've been thinking about how to display the newest array (because the array list would update from time to time.). I think there's a default function to it but I can't find it. Anyone knows it?

var bgImg = new Array();

bgImg[0] = "background.jpg";
bgImg[1] = "background2.jpg";
bgImg[2] = "background3.jpg";
bgImg[3] = "background4.jpg";
2
  • 2
    Please clarify what you're asking here. Commented Nov 13, 2010 at 17:44
  • Sorry about that, it's just that English is my second language. Commented Nov 13, 2010 at 17:49

2 Answers 2

1

If you want the last element of the array,

>>> a = ['background1','background2'];
["background1", "background2"]
>>> b = a[a.length-1]
"background2"

You shouldn't need to manually assign indexes. Just do bgImg.push('background2.jpg'), and it will mutate the array for you. In your case the syntax would be...

var last = bgImg[bgImg.length-1]

If you want the newest then you need to make a variable and set it with whatever you update when you push the newest one, if it doesn't become the last one.

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

Comments

1

You could create a little object to handle this for you.

function creatImageState() {
    var images = [];
    return {
        get latest() {                    
            return images[images.length - 1];
        },
        set latest (value) {
            images.push(value);
        }
    };
}

var s = creatImageState();

s.latest = "a.png";
s.latest = "b.png";

alert(s.latest);

IE doesn't support getters and setters so you probably need to use this.

function creatImageState() {
    var images = [];
    return {
        getLatest : function() {                    
            return images[images.length - 1]
        },
        setLatest : function(value) {
            images.push(value);
        }
    };
}

var s = creatImageState();

s.setLatest("a.png");
s.setLatest("b.png");

alert(s.getLatest());

Comments

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.