Javascript For Loop mixed with if

0

This script does not work properly. I can not get the times that exist in Qui of a few (nn1), two (nn2) and three (nn3) correctly. In that string Qui, there are 7 ones (1), with which nn1 should be 7. There are 2 deuces, nn2 should be 2 and there are 5 treses. whereby nn3 should be 5.

On the other hand, when I run javascript, nn1, nn2 and nn3 go from 1 to 14, and Quic, although it should be each of the Qui characters, in the program it seems that it only has the value of 3.

<script>
n=0, nn1=0, nn2=0, nn3=0, s=0, w=0;
Qui = "13231132311113";
Quic="";
for (w=0;w<14;w++){
       Quic = Qui.substr(w,1);
       if (Quic = 1){ nn1=nn1+1;}
       if (Quic = 2){ nn2=nn2+1;}  
       if (Quic = 3){ nn3=nn3+1;} 
       document.write(n + " " + nn1 + " " + nn2 + " " + nn3 + " " + Qui + "&nbsp &nbsp" + Quic + "<br>");
       n=n+1; 
}
</script>
    
asked by csvicuna 12.06.2018 в 18:02
source

2 answers

1

To make comparisons, you have to use the operator ==

<script>
  n = 0, nn1 = 0, nn2 = 0, nn3 = 0, s = 0, w = 0;
  Qui = "13231132311113";
  Quic = "";
  for (w = 0; w < 14; w++) {
    Quic = Qui.substr(w, 1);
    if (Quic === 1) {
      nn1 = nn1 + 1;
    }
    if (Quic === 2) {
      nn2 = nn2 + 1;
    }
    if (Quic === 3) {
      nn3 = nn3 + 1;
    }
    document.write(n + " " + nn1 + " " + nn2 + " " + nn3 + " " + Qui + "&nbsp &nbsp" + Quic + "<br>");
    n = n + 1;
  }
</script>

That's how it should work

    
answered by 12.06.2018 в 18:19
0

You have a couple of problems in your code.

On the one hand, in your comparisons you are using = which is an assignment operator, not a comparator. In javascript it is recommended to use === since it makes a comparison of value and type of value.

On the other hand, the impression of results must be taken out of the loop, to show these once all the input characters have been processed.

The resulting code would be something like this:

<script>
n=0, nn1=0, nn2=0, nn3=0, s=0, w=0;
Qui = "13231132311113";
Quic="";
for (w=0;w<14;w++){
       Quic = Qui.substr(w,1);
       if (Quic === "1"){ nn1=nn1+1;}
       if (Quic === "2"){ nn2=nn2+1;}  
       if (Quic === "3"){ nn3=nn3+1;} 
       
       n=n+1; 
}
document.write(n + " " + nn1 + " " + nn2 + " " + nn3 + " " + Qui + "&nbsp &nbsp" + Quic + "<br>");
</script>

If what you really want is to show the process, simply leave the line that shows the data inside the loop where you had it:

<script>
n=0, nn1=0, nn2=0, nn3=0, s=0, w=0;
Qui = "13231132311113";
Quic="";
for (w=0;w<14;w++){
       Quic = Qui.substr(w,1);
       if (Quic === "1"){ nn1=nn1+1;}
       if (Quic === "2"){ nn2=nn2+1;}  
       if (Quic === "3"){ nn3=nn3+1;} 
       document.write(n + " " + nn1 + " " + nn2 + " " + nn3 + " " + Qui + "&nbsp &nbsp" + Quic + "<br>");
       n=n+1; 
}

</script>
    
answered by 12.06.2018 в 18:18