I have an object that contains 2 arrays up
and down
, these values should be linked to up and down keys, ticking up you should move through the up
array, if you tick down you should through any up
tick values (if up
ticks have happened) through to the down
array and vice-versa.
I've managed to create a version of this but having some issues getting undefined
at what I would deem to be the cross-over point between up and down. Could someone possibly provide me with some advice on how to make this more robust and solve the undefined
issue? Should I start at -1 for my counter or what should the approach be?
JS
var prices = {
"up" : [
{"r": 10.25, "f" : "10.25"},
{"r": 10.50, "f" : "10.50"},
{"r": 10.75, "f" : "10.75"},
{"r": 11.00, "f" : "11.00"},
{"r": 11.25, "f" : "11.25"},
{"r": 11.50, "f" : "11.50"},
{"r": 11.75, "f" : "11.75"},
{"r": 12.00, "f" : "12.00"},
{"r": 12.25, "f" : "12.25"},
{"r": 12.50, "f" : "12.50"}
],
"down": [
{"r": 7.50, "f" : "7.50"},
{"r": 7.75, "f" : "7.75"},
{"r": 8.00, "f" : "8.00"},
{"r": 8.25, "f" : "8.25"},
{"r": 8.50, "f" : "8.50"},
{"r": 8.75, "f" : "8.75"},
{"r": 9.00, "f" : "9.00"},
{"r": 9.25, "f" : "9.25"},
{"r": 9.50, "f" : "9.50"},
{"r": 9.75, "f" : "9.75"}
]
};
var $btns = $('.js-btn');
var counter = -1;
$btns.on('click', function(event) {
var dir = $(event.currentTarget).data('dir');
if(dir === 'up') {
if(counter >= -1) {
console.log(prices[dir][++counter]);
} else {
console.log(prices['down'][prices['down'].length + counter++]);
}
}
if(dir === 'down') {
if(counter <= -1) {
console.log(prices[dir][prices[dir].length + counter--]);
} else {
console.log(prices['up'][--counter]);
}
}
});
JS Fiddle http://jsfiddle.net/kyllle/7Lznj00w/
In order to ensure that your array accesses are valid, you want the array index to be in the range [0, arr.length-1]
. If you attempt to access a JavaScript array at an invalid index, you'll get undefined.
You can initialize your upIndex
and downIndex
to 0
(the first element in the list). Now suppose you want the next element in the up array. You can update upIndex as follows
upIndex = (upIndex + 1) % prices.up.length
The %
operator gives you the remainder after division (so 3 % 2
is 1
since 3/2
leaves a remainder of 1
). So if you are already at the last index in up
it will start you over at the beginning. The last index in up is 9, and up.length is 10, so upIndex = (9 + 1) % 10 = 0
, ensuring that you always stay within the bounds of the array.