使用取模运算符或 Js 通过数组自增和自减
Increment and Decrement through array using modulus operator or Js
通过阅读另一个问题,我能够弄清楚如何通过我的数组递增。现在我似乎无法弄清楚如何递减,因为我的值被设置回 0。我试图避免循环。
我希望达到的顺序是:
Increment ---- "/", "/about", "/list" <-- list 是结尾。递减只是倒带。减量只是每次后退 1 步。
let i = 0;
let stuff =["/", "about","list"];
next() {
this.props.dispatch(increaseCounter())
i = (i+1)%stuff.length;
}
prev() {
this.props.dispatch(decreaseCounter())
i = (i-1)%stuff.length; <------This gets wonky once I reach the end of my array.
}
如果您希望 next()
在 0
和 2
之间递增 i
并且 prev()
在 2
和 [=13] 之间递减=] 您可以使用以下内容:
next() {
this.props.dispatch(increaseCounter());
i = Math.min(i + 1, stuff.length - 1);
}
prev() {
this.props.dispatch(decreaseCounter());
i = Math.max(i - 1, 0);
}
%
的问题在于它是截断除法的余数运算符,而不是 modulo 底除法的余数运算符。当除数 (i-1
) 变为负数时,结果也变为负数。您可以使用
if (--i < 0) i = stuff.length - 1;
或
i = (i + stuff.length - 1) % stuff.length;
相反(但仅适用于预期范围内的 i
输入值)
通过阅读另一个问题,我能够弄清楚如何通过我的数组递增。现在我似乎无法弄清楚如何递减,因为我的值被设置回 0。我试图避免循环。
我希望达到的顺序是:
Increment ---- "/", "/about", "/list" <-- list 是结尾。递减只是倒带。减量只是每次后退 1 步。
let i = 0;
let stuff =["/", "about","list"];
next() {
this.props.dispatch(increaseCounter())
i = (i+1)%stuff.length;
}
prev() {
this.props.dispatch(decreaseCounter())
i = (i-1)%stuff.length; <------This gets wonky once I reach the end of my array.
}
如果您希望 next()
在 0
和 2
之间递增 i
并且 prev()
在 2
和 [=13] 之间递减=] 您可以使用以下内容:
next() {
this.props.dispatch(increaseCounter());
i = Math.min(i + 1, stuff.length - 1);
}
prev() {
this.props.dispatch(decreaseCounter());
i = Math.max(i - 1, 0);
}
%
的问题在于它是截断除法的余数运算符,而不是 modulo 底除法的余数运算符。当除数 (i-1
) 变为负数时,结果也变为负数。您可以使用
if (--i < 0) i = stuff.length - 1;
或
i = (i + stuff.length - 1) % stuff.length;
相反(但仅适用于预期范围内的 i
输入值)