Reputation: 119
My code is giving unexpected output. I am trying to return boolean value if input is entered as RGB ("rgb(255,255,255)").
Can someone tell me where am I going wrong?
function checkRGB(input) {
var i, elem, validRGB;
validRGB = false;
// if input is within “rgb(”x,x,x“)“, should continue to execute
if((input.slice(0, 4) === "rgb(") && (input.slice(-1) === ")")) {
// Getting only "x, x, x," elements and make them array;
elem = input.slice(4, -1).split(",");
// Looping through array elements
for(i = 0; i < elem.length; i++) {
elem[i] = parseInt(elem[i]);
// if array elements > 0 and <= 255 , return true;
if((elem[i] >= 0 && elem[i] <= 255)) {
validRGB = true;
}
}
}
return validRGB;
};
checkRGB("rgb(0,0,300)"); // returns true; should be false;
checkRGB("rgb(0,-1,0)"); // returns true; should be false;
Your help is greatly appreciated! thank you
Upvotes: 1
Views: 732
Reputation: 144
The returning value is determined by last elem.
+maybe my answer is not enough The problem is, you are examining three values. On example rgb(0,0,300), second loop makes validRGB to true, and third one would be skipped because 300 is not bigger than 0 nor less then 255.
On the other hand, "rgb(0,-1,0", second loop makes validRGB to false. but It changed true at third loop.
Upvotes: 0
Reputation: 3387
Try this code
as per your code if last one of color(B in RGB) is <=255
it will returns true.
so you need to code as if in any case if the color code >255
and '<0' returns false
so make some changes to it if in any case it will be false
then break the code.
alert(checkRGB("rgb(0,0,300)"));
function checkRGB(input) {
var i, elem, validRGB;
validRGB = false;
// if input is within “rgb(”x,x,x“)“, should continue to execute
if((input.slice(0, 4) === "rgb(") && (input.slice(-1) === ")")) {
// Getting only "x, x, x," elements and make them array;
elem = input.slice(4, -1).split(",");
// Looping through array elements
for(i = 0; i < elem.length; i++) {
elem[i] = parseInt(elem[i]);
// if array elements > 0 and <= 255 , return true;
if((elem[i] >= 0 && elem[i] <= 255)) {
validRGB = true;
}
else
{
validRGB = false;
break;
}
}
}
return validRGB;
};
Upvotes: 0
Reputation: 1
Use an else
statement and break
the loop
if ((elem[i] >= 0 && elem[i] <= 255)) {
validRGB = true;
}
else {
validRGB = false;
break;
}
Upvotes: 2