When comparing two strings I always get an error (They are not the same) - Javascript - DOM

0

I have a problem, when comparing two strings " clickedColor " and " pickedColor " I always get the error that they are not the same and I can not see why. I appreciate all the help possible.

Here the codepen: Codepen

ColorRandomizer generates three random values R G and B and puts them into an Array of squares, then the assigned color puts it into an Array of Strings (squareColor).

pickedColor takes a random value inside the squareColor Array and is assigned

CreateClickEvents is where it gives me that it is always false, after creating the click events. In these, if the background is equal to pickedColor it should be correct, if not, error. The thing is that I ALWAYS MISS ERROR

Here I paste the code of the js file

var squares = document.querySelectorAll(".square");
var squareColor = [];

var colorToGuess = document.querySelector("#colorToGuess");
//Color variables
var R = 0;
var G = 0;
var B = 0;

//console.log(pickedColor);

colorRandomizer();
var pickedColor = squareColor[Math.floor(Math.random() * 6)];
createClickEvents();
colorToGuess.textContent = pickedColor;

//Randomize boxes with colors and fill squareColor[]
function colorRandomizer () {
    for (var i = 0; i <= squares.length - 1; i++) {
        R = Math.floor(Math.random() * 256);
        G = Math.floor(Math.random() * 256);
        B = Math.floor(Math.random() * 256);
        squares[i].style.backgroundColor = "rgb( " + R + ", " + G + ", " + B + ")";
        squareColor.push("rgb( " + R + ", " + G + ", " + B + ")");
        //console.log(squareColor[i]);
            }
}

function createClickEvents () {
    for (var i = 0; i <= squares.length - 1; i++) {
        squares[i].addEventListener("click", function(){
            var clickedColor = this.style.backgroundColor;
            if(clickedColor === pickedColor){
                alert("Correct!");
            }else{
                alert("Wrong!");
                this.style.backgroundColor = "#232323";
            } 
        })
    }


}

Thank you very much!

    
asked by Varox 27.02.2018 в 19:10
source

2 answers

1

Good friend, seeing your codepen I realized that the error is the blank spaces.

First delete all the spaces generated here

squares[i].style.backgroundColor = "rgb("+ R +", "+ G +", "+ B +")";
squareColor.push("rgb("+ R +", "+ G +", "+ B +")");

Second eliminate those from clickedColor

clickedColor = clickedColor.replace(/ /g,'');

Third remove those from pickedColor

pickedColor = pickedColor.replace(/ /g,'');
    
answered by 27.02.2018 / 19:29
source
1

The problem occurs when you assign the backgroundColor to the element with rgb( r, g, b) format, it corrects itself with rgb(r, g, b) , removes the spaces so that the comparison is true.

    
answered by 27.02.2018 в 19:35