user45867 user45867 - 20 days ago 5
Javascript Question

Javascript - quick way to check if 10 variables are between 0 and 1?

I know there's probably an easy loop for this, but can't think of it.

I have 10 scores, and I need to validate them by making sure they are between 0 and 1 (plenty of decimals).

The input is pretty loose, so blank, null, alphanumeric values can be in there.

Right now I simply have

if (!(score1>=0 && score1<=1)){var result="error"} else
if (!(score2>=0 && score2<=1)){var result="error"} else
if (!(score3>=0 && score3<=1)){var result="error"} ...


Maybe not the most elegant formatting but -- there's got to be a way to loop through this, right?

Answer

Just use every MDN, and place your numbers in an array.

var score1 = 0.89;
var score2 = 0.75;
var score3 = 0.64;
var booleanResult = [score1,score2,score3].every(s => s >= 0 && s<= 1);
console.log(booleanResult);

This answer uses an arrow function SO Docs

Comments