0

As a beginner of javaScript coding I wrote some code and when I was trying to run the code it was executing and went to the else block every time instead of the if block. I found where the problem was occurring but I didn't know how to solve it. I got spaces between the numbers when I clicked the color, yet the else statement was always executing. You can see my problem below to get some idea. How can I make this code work? Please help me, thanks in advance.

var colors=[
      "rgb(255,0,0)",
      "rgb(255,255,0)",
      "rgb(0,255,0)",
      "rgb(0,255,255)",
      "rgb(0,0,255)",
      "rgb(255,0,255)",
 ];

var squares=document.querySelectorAll(".square");

var pickedColor=colors[4];

for(var i=0;i<squares.length;i++){

   squares[i].style.background=colors[i];

   squares[i].addEventListener("click",function(){

      var clickedColor=this.style.back
      console.log("clicked color is"+clickedColor);
      console.log("picked color is "+pickedColor);

      if(clickedColor===pickedColor)
      {
         alert("correct");
      }
      else
      {
         alert("wrong");
      }
    })
 }

The Problem: The rgb below was not matched and spaces were added. How can we remove those spaces?

clicked color is rgb(0, 0, 255), picked color is rgb(0,0,255)

Eric
  • 1,210
  • 8
  • 25
  • This might help you: https://stackoverflow.com/questions/10800355/remove-whitespaces-inside-a-string-in-javascript – ADyson Jun 30 '17 at 16:19
  • I'm a bit surprised you get anything from `this.style.back`... – Heretic Monkey Jun 30 '17 at 19:32
  • Possible duplicate of [Remove whitespaces inside a string in javascript](https://stackoverflow.com/questions/10800355/remove-whitespaces-inside-a-string-in-javascript) – Heretic Monkey Jun 30 '17 at 19:33

3 Answers3

1

I'm no javascript expert but you might have better luck if in your if statement you use == instead of ===.

brian
  • 155
  • 1
  • 7
0

You could split the clickedColor value into a string array and then set its value to the join of the array without a delimiter.

e.g. -

var ccArray = clickedColor.split(" "); // split by space character
var newValue = ccArray.join(""); // join with a zero length` delimiter

   then, newValue should be used for the comparison
0

So multiple things,
One: typically stick to ==, as Guest01 has stated.
Two: Your Array shouldn't have the last comma:

var colors=[
      "rgb(255,0,0)",
      "rgb(255,255,0)",
      "rgb(0,255,0)",
      "rgb(0,255,255)",
      "rgb(0,0,255)",
      "rgb(255,0,255)"
    ];

Three: To remove the spaces you could use string.replace(/\s/g, '')