简体   繁体   中英

Write a better IF return statement in JavaScript

I had this quick question about IF statements and how it can be used with arrays.

I'm trying to get an element from an array, but if the index is bigger than 24, subtract 24 from the index. Here's what I've tried, but I find it generally a bit long.

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)

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

Arr[Index > 24 || Index - 24];

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.

You can use the modulus operator ( % ):

Arr[Index % 25] // forces Index to be between 0 and 24 inclusive

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

Arr[(Index + 25) % 25]

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

Arr[Index % Arr.length]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM