user4227915
user4227915

Reputation:

Setting value to objects' property from its function doesn't work

I'm trying to use new_Color.next() to each time it is called return a different color in array-order. But it always return blue. What did I wrong?

var new_Color = {
    index: 0,
    colors: ['blue', 'lightblue', 'darkblue'],
    next: function() {
        this.index = this.index + 1 < this.colors.length? 0: this.index + 1;
        return this.colors[this.index];
    }
};

Thanks in advance.

Upvotes: 3

Views: 38

Answers (1)

Oka
Oka

Reputation: 26385

You're always resetting the index to 0 because (0) + 1 is less than the length. Flip the comparison operator, and make it length - 1.

var new_Color = {
    index: 0,
    colors: ['blue', 'lightblue', 'darkblue'],
    next: function() {
        //                          v right here
        this.index = this.index + 1 > this.colors.length - 1 ? 0 : this.index + 1;
        return this.colors[this.index];
    }
};

If you want to start with blue, make your initial index -1.

Upvotes: 3

Related Questions