简体   繁体   中英

How to detect if a user input has been repeated?

I'm trying to make hangman in javascript and I want to check if the user has used a letter already. I made a var letterGuessValue = to 0 and if they add an input it = 1. I know this would say know to everything if i got it to work (it doesn't even do anything) but am I on the right track maybe? Here's my code. http://jsbin.com/aWOnAfe/5/edit

I would say add an input to a list and whenever they add another input (aka letter), check this list to see if it is already in there. If it is, then its because they've already used that letter before. If not, then it is a new letter.

I don't see where the difficult part is.

http://jsfiddle.net/DerekL/jgqQ9/

Sample code

var used = {};
$("input").keyup(function(){
    var val = this.value;
    alert( used[val] ? "Used" : "Not used" );
    this.value = "";
    used[val] = true;
});

How it works

Assign true to used.LETTER when a letter is entered. Before assigning it though, if it was undefined then it hasn't been used. If it is true then it is used.

Sometimes developers tend to use an Array to record pressed keystrokes when doing key combinations, but in this case, iterating an Array would require both more memory and computation power. A simple object is an enough fit.

Use an array to store all of the used letters and function like this to add new ones.

var inputs = []

function addLetter(letter){
   var used = false;
   for(var i = 0; i < inputs.length; i++){
       if(inputs[i] == letter){
           used = true;   
           break; 
       }
   }
   if(!used){
       inputs.push(letter);
   }
}

The easiest way is to append each letter to a string, like this:

var letters = '';
var letterPressed = 'X'; // uppercase it if appropriate for your language

if (letters.indexOf(letterPressed) > -1)
{
    // you already pressed it
}
else
{
    letters += letterPressed;
}

You can also use an array to store your list of presses, although IMO that's overkill.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM