获取数组的元素,无论索引的大小如何

Get an element of an array no matter the size of the index

本文关键字:索引 数组 元素 获取      更新时间:2023-09-26

它存在一些带有函数的库,允许我做一些类似于我在下面发布的代码示例的事情?我搜索没有成功,洛达什没有这样的方法。也许将其添加到他们的 API 中会很好。提前谢谢。

var array = [1, 2, 3, 4, 5];
functionX(array,  6) === 2;
functionX(array, -1) === 5;
functionX(array, -7) === 4;

为什么你想要一个库函数,当你可以尝试类似的东西时

function functionX(array, index) {
    index = index % array.length;
    return index >= 0 ? array[index] : array[array.length + index]
}

演示:小提琴