samedi 21 décembre 2019

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, remove 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 take away 24 from it, then return that value from the array.

Hope you can help.

Aucun commentaire:

Enregistrer un commentaire