gpt4 book ai didi

javascript - 从其功能设置对象属性的值不起作用

转载 作者:行者123 更新时间:2023-11-29 10:39:13 26 4
gpt4 key购买 nike

我正在尝试使用 new_Color.next() 每次调用它时按数组顺序返回不同的颜色。但它总是返回 blue。我做错了什么?

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];
}
};

提前致谢。

最佳答案

您总是将 index 重置为 0 因为 (0) + 1 小于 length。翻转比较运算符,使其成为 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];
}
};

如果你想从blue开始,让你的初始索引-1

关于javascript - 从其功能设置对象属性的值不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31990585/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com