1

I have four IF statements, is it possible to rewrite this into a neater loop, where the [i] may be '4' or higher.

if (typed.length == 1 && c.charAt(0) == typed[0]) { 
    //something ; 
    return false;
}

if (typed.length == 2 && c.charAt(0) == typed[0] 
    && c.charAt(1) == typed[1]) {  
    //something ; 
    return false;
}

if (typed.length == 3 && c.charAt(0) == typed[0] 
    && c.charAt(1) == typed[1] && c.charAt(2) == typed[2]) {  
    //something ; 
    return false;
}

if (typed.length == 4 && c.charAt(0) == typed[0] 
    && c.charAt(1) == typed[1] && c.charAt(2) == typed[2] 
    && c.charAt(3) == typed[3]) {  
    //something ; 
    return false;
}
1
  • is the order of c and typed always the same, or can c contain a randomly set characters that may be contained in typed? Commented Feb 7, 2011 at 4:00

4 Answers 4

3

Looks to me like something like this should to it:

if (c.substr(0, typed.length) == typed)

Possibly typed.join() if typed is an array.

Sign up to request clarification or add additional context in comments.

8 Comments

I agree with this method, but Brandon was asking specifically for a loop.
@Yanick I have to assume a lot about this question, since there's little info... :)
@Jason The OP doesn't necessarily always know what he wants... ;)
@+1: beat me to it! because the question can be simplified as checked whether "typed" is same as a predefined "c"
brilliant! thanks, I don't need the loop anymore with your solution.
|
1

Try this

for(var x=0; x<typed.length; x++)
{
   if(c.chatAt(x)!=typed[x]) { return false; }
}
return true;

Comments

0
for (var i=1; i<=4; ++i){
  if (typed.length!=i) continue;
  var OK = true;
  for (var j=0;j<i;++j){
    OK = OK && (c.charAt(0)==typed[j]);
  }
  if (OK){
    // something
    return false;
  }
}

Comments

0

Forget about two nested loops, or assuming c and typed are "ordered", just look for the char in c

for (var i=0; i<typed.length; i++) {
   if (c.indexOf(typed.charAt(i)) >= 0) {  // or c.indexOf(typed.charAt(i)) == i
      return false;
   }
}
return true;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.