I'm trying to make function that will return next or previous item in array, based on parameter "direction". For example I have array = ['ferrari', 'bmw', 'merc', 'bugatti'] and I want my my function to return 'bugatti' IF currentPointer = 'ferrari' and direction = 'left'
nextPrev(array,direction,currentPointer)
In php we have function next() which moves the internal pointer ... but I don't know how to do it in javascript ...
The basic idea would be:
function nextPrev(array, direction, currentPointer) {
var index = array.indexOf(currentPointer);
if (direction=="left") {
return array[index == 0 ? array.length-1 : index-1];
} else if (direction=="right") {
return array[index == array.length-1 ? 0 : index+1];
} else {
// default action or throw error
}
}
You can reorganize this a bit:
function nextPrev(array, direction, currentPointer) {
var index = array.indexOf(currentPointer);
var len = array.length;
if (direction=="left") {
index--;
} else if (direction=="right") {
index++
} else {
// default action or throw error
}
return array[(index + len) % len];
}
You might want to add a check that array.indexOf
returns a valid index (in case currentPointer
contains something not in array
).
You can write something like this:
function makeDirectionalIterator(array){
var currIndex = 0;
return {
nextPrev: function(direction){
if(direction === 'left') {
return currIndex < array.length-1 ?
{value: array[++currIndex], done: false} :
{done: true};
}
else {
return currIndex > 0 ?
{value: array[--currIndex], done: false} :
{done: true};
}
},
current: function() {
return { value: array[currIndex] };
}
}
}
Then you can use it like the following
var itr = makeDirectionalIterator(array);
itr.current().value;
itr.nextPrev('left').value;
itr.nextPrev('left').done;
Try Something like this.
Using the numerical locations of the array and conditionally cycle through:
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'"); } }
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.