bcm
bcm

Reputation: 5500

Appending conditions in a numerical loop (JavaScript)

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;
}

Upvotes: 1

Views: 148

Answers (4)

Yanick Rochon
Yanick Rochon

Reputation: 53626

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;

Upvotes: 0

Phrogz
Phrogz

Reputation: 303530

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;
  }
}

Upvotes: 0

deceze
deceze

Reputation: 522626

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.

Upvotes: 3

Jason
Jason

Reputation: 15378

Try this

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

Upvotes: 1

Related Questions