Dan
Dan

Reputation: 597

how to pick a new index of an array by each click

I have a function that it includes an array of colours, and there is a button and a text tag. So after each click, the function take the current index of the array, show it in the text and add one to the index number so next time the next index will be shown.

Here is my code:

var mycolor = 0;

var color = function() {
    var list = ["red", "blue", "green"];    
    return list[mycolor];
    mycolor++;
};

function run(){
    $(".demo").text(color());
}

JSFIDDLE

Any idea? how to fix it? currently it only shows the first index, it does not update it the variable.

Upvotes: 0

Views: 59

Answers (5)

Nice-Guy
Nice-Guy

Reputation: 1524

This is the only one that will work because it's the only code that includes a click event.

var mycolor = 0;
var maxcolor = 0
var color = function() {
    var list = ["red", "blue", "green"];    
    maxcolor = list.length;
    if((mycolor + 1) > maxcolor)
    {
        mycolor = 0
    }
    return list[mycolor++];

};

$(".demo").text('on', 'click', color());

Upvotes: 0

steve_gallagher
steve_gallagher

Reputation: 3898

How about this:

var mycolor = 0;
var list = ["red", "blue", "green"]; 

var color = function() {
    return list[mycolor];
};

function run(){
    $(".demo").text(color());
    mycolor++;
    if(mycolor > 2) {
        mycolor = 0;
    }
}

mycolor isn't getting update because you incrementing it after you already have returned from the function.

Upvotes: 0

tjg184
tjg184

Reputation: 4676

Your return is too early. You also need to handle when mycolor is past the array length.

var color = function() {
    var list = ["red", "blue", "green"];    

    if (mycolor >= list.length)
       mycolor = 0;

    return list[mycolor++];
};

An alternative way of writing the above would be the following:

var color = function() {
    var list = ["red", "blue", "green"];    
    return list[mycolor++ % list.length];
};

function run(){
    $(".demo").text(color());
}

Upvotes: 1

Aqib1604
Aqib1604

Reputation: 302

This is for

var mycolor = 0;
var maxcolor = 0
var color = function() {
    var list = ["red", "blue", "green"];    
    maxcolor = list.length;
    if((mycolor + 1) > maxcolor)
    {
        mycolor = 0
    }
    return list[mycolor++];
    
};

function run(){
    $(".demo").text(color());
}

infinite version.

Upvotes: 1

alex
alex

Reputation: 490263

You are incrementing post return, which guarantees the code isn't executed.

Try something like...

var color = function() {
    var list = ["red", "blue", "green"];    
    return list[mycolor++];
};

Which returns the number and then increments it. You should probably do % list.length to so calling beyond the length of your array will wrap the results instead of returning undefined (unless of course, that's what you want).

Upvotes: 0

Related Questions