我正在尝试根据参数“ direction”使函数返回数组中的下一个或上一个项目。例如,我有array = ['ferrari','bmw','merc','bugatti'],并且我希望我的函数在if currentPointer ='ferrari'和direction ='left'时返回'bugatti'。
nextPrev(array,direction,currentPointer)
在php中,我们具有函数next()来移动内部指针...但是我不知道如何在javascript中执行此操作...
尝试这样的事情。
使用数组的数字位置并有条件地循环遍历:
var array = ['ferrari', 'bmw', 'merc', 'bugatti'];
var returnedElement = nextPrev(array, "left", "ferrari");
// Show Returned Value (Console)
console.log(returnedElement);
function nextPrev(array, direction, currentPointer) {
var arraySize = array.length - 1;
var currentIndex = array.indexOf(currentPointer);
if (direction === "left") {
// Decrease array by one
if (currentIndex == 0) {
// Return Previous (Max Array)
return array[arraySize]
} else {
return array[currentIndex - 1]
}
} else if (direction === "right") {
// Increase array by one
if (currentIndex == arraySize) {
// Go to zero position
return array[0]
} else {
return array[currentIndex + 1]
}
} else {
console.log("Use either 'left' or 'right'");
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句