Reputation: 18198
My last question asked for running once without the use of booleans. I decided I needed booleans but not a lot of variables since that would be messy.
So let's say I have this:
var counter = 0;
$(function() {
$('#typing').keyup(function() {
switch($(this).val().toLowerCase()) {
case 'test':
// DO THIS EVERYTIME TEST CASE IS CALLED
$('#test').fadeOut("fast", function() {
$(this).html("<span class='green'>That's correct!</span>").fadeIn("fast");
});
// DO THIS ONCE AND ONLY ONCE
count++;
}
});
});
Basically, it's part of 'percent complete' application where a user tries to type all cases I make available. So if a user types test twice... on the first run of case test
it would add 1 to the counter but on the SECOND run of case test
it would NOT add to counter.
I don't want to make it to add a lot of booleans for each case because that would be messy.
Get it? :)
My idea is to make an array and per each case that I add it would add alltogther. So array[0] would be case test
. Then I on my first try I would set array[0] to 1.. then create a FOR-LOOP on each case array to add up for total. This is a good idea?
The only problem is I don't know how to make a per case array.
Upvotes: 1
Views: 263
Reputation: 342695
A simple way would be to use an object literal as the counter variable, and once a case is hit assign the value true
:
var counter = {};
...
case 'test' : counter[$(this).val()] = true;
Alternatively, check if the 'case' has already been stored in a plain old boring array:
var counter = [];
...
case 'test' :
if(!$.inArray($(this).val(), counter)) {
counter.push($(this).val());
}
Upvotes: 2
Reputation: 97641
Doing exactly what you asked:
var validKeys = ['test', 'testing', '1337'];
var checkedKeys = {};
function getCount() {
var counter = 0;
$.each(validKeys, function(index, value) { //jQuery.each, for neat array iteration
if(checkedKeys[value])
counter++;
});
return counter;
}
$(function() {
$('#typing').keyup(function() {
var val = $(this).val().toLowerCase();
if(val == 'test') { //neater than a switch statement, often
// DO THIS EVERYTIME TEST CASE IS CALLED
$('#test').fadeOut("fast", function() {
$(this).html("<span class='green'>That's correct!</span>").fadeIn("fast");
});
}
checkedKeys[val] = true;
});
});
Upvotes: 0