用 JavaScript 编写更好的 IF 返回语句

QSm*_*lly 1 javascript arrays if-statement

我有一个关于 IF 语句以及它如何与数组一起使用的快速问题。

我试图从数组中获取一个元素,但如果索引大于 24,则从索引中减去 24。这是我尝试过的,但我发现它通常有点长。

const Arr = ["Number 0", "Number 1", "Number 2", ...];

let Index = 4;
Arr[Index > 24 ? Index - 24 : Index];
// "Number 4"

Index = 25;
Arr[Index > 24 ? Index - 24 : Index];
// "Number 1" (because 25 - 24 = 1)
Run Code Online (Sandbox Code Playgroud)

I was wondering if it could be done like this or another way shorter than above.

Arr[Index > 24 || Index - 24];
Run Code Online (Sandbox Code Playgroud)

FYI: The index should stay the same if it's less than 24, but if the index is 25 or more, it would need to subtract 24 from it, then return that value from the array.

Hope you can help.

Poi*_*nty 6

You can use the modulus operator (%):

Arr[Index % 25] // forces Index to be between 0 and 24 inclusive
Run Code Online (Sandbox Code Playgroud)

If it's possible that Index ends up less than zero, you can do

Arr[(Index + 25) % 25]
Run Code Online (Sandbox Code Playgroud)

to "normalize" the value into the desired range. Of course in general you'd probably want

Arr[Index % Arr.length]
Run Code Online (Sandbox Code Playgroud)