2

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?

user45867
  • 887
  • 2
  • 17
  • 30

9 Answers9

9

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:


Alternatively, this is an example of using every with a classic function callback

var score1 = 0.89;
var score2 = 0.75;
var score3 = 0.64;
var booleanResult = [score1,score2,score3].every(function(s){ return s >= 0 && s<= 1 });
console.log(booleanResult);
Graham
  • 7,431
  • 18
  • 59
  • 84
Travis J
  • 81,153
  • 41
  • 202
  • 273
  • 1
    Great answer, but important to note that this uses ES6 features which may not be compatible with OP's target browsers. – samrap Nov 15 '16 at 22:52
  • 1
    @samrap - Yes, that is why I included the link to the arrow function topic in Docs, it also includes which browsers and versions support arrow functions. That said, I included an alternative example here to see how a classic callback would be used, although I assume that many users are familiar with this approach as well. – Travis J Nov 16 '16 at 00:16
1

You can just create an array var numbersArray = [var1, var2, var3 ...] iterate through the array and check the if, you can create a "flag" variable with a boolean and if any of the numbers result in error then change the flag value and break the for...

That's it, pretty straightforward.

samrap
  • 5,595
  • 5
  • 31
  • 56
LuisKx
  • 312
  • 1
  • 3
  • 7
1

you could try something like this

var array = [var1, var2, varn ...];
for (let arr of array) {
    if (typeof arr === 'number')
        if (arr >= your condition)
            ... the rest of your code here
}
TyAnthoney
  • 278
  • 4
  • 12
1

You can do it this way:

for (i = 1; i <= 10; i++)
{
    if (!(window["score"+i.toString()]>=0 && window["score"+i.toString()]<=1)){var result="error"}
}

Here is a fiddle to prove the concept: https://jsfiddle.net/gL902rtu/1/

And as mentionned by @Rick Hitchcock, the score variable has to be global (see the fiddle for example)

Proof of concept:

score1 = 0.5;
score2 = 0.1;
score3 = 0.5;
score4 = 0.8;
score5 = 0.9;
score6 = 0.4;
score7 = 0.10;
score8 = 0.4;
score9 = 0.5;
score10 = 0.8;
result = "noerror";
for (i = 1; i <= 10; i++){
  if (!(window["score"+i.toString()]>=0 && window["score"+i.toString()]<=1)){ 
    result="error"
  }
}

console.log(result);

Note that this would work with your code but the easiest way would be for sure to store your score in a array and loop trough it, it's pretty much what arrays are for.

You can have more information about array over here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Yann Chabot
  • 4,789
  • 3
  • 39
  • 56
  • 1
    `toString()` isn't necessary here. (Also, you should point out that this works only if the variables are in the global scope.) – Rick Hitchcock Nov 15 '16 at 22:39
0

I would use a function for this, where the first argument is minimum, second is maximum, then the rest are numbers to check, then using .filter() to find invalid numbers:

function CheckRange(min, max) {
    if (arguments.length > 2) {
        var args = Array.prototype.slice.call(arguments);
     return args.slice(2).filter(function(x) {
            return x < min || x > max;
        }).length == 0;
    }
    return true;
}
console.log(CheckRange(0, 1, 0.25, '', null, 0.7, 0.12, 0.15));

In the above code empty or null are treated as valid, easy enough to disallow them if needed.

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
0
const scores = [0.1, 0.2, 0.3, 0.4, 1, 2, 3, 4, 5, 6];

scores.forEach(function(score){
    // http://stackoverflow.com/questions/3885817/how-do-i-check-that-a-number-is-float-or-integer
    let isFloat = ( Number(score) === score && score % 1 !== 0 );

    if (isFloat && (score > 0 && score < 1))
        console.log("It's correct!");
});
Jordan Enev
  • 16,904
  • 3
  • 42
  • 67
0

Putting your scores into an array would be the best starting point. You can do this easily like:

var allScores = [score1, score2, score3];

Once you have an array, if you are targeting a platfrom with ES5 support check here then you can use the filter function of an array:

var errorScores = allScores.filter(function(s) {
  return !(parseInt(s) >= 0 && parseInt(s) <= 1)
});

if (errorScores.length > 0) {
  // Do some error handling.
}

Here is an example of this on code pen

Alternatively, if you can't use filter then you can do a loop like this:

for (var i = 0; i < allScores.length; i++) {
  var score = allScores[i];
  if (!(parseInt(score) >= 0 && parseInt(score) <= 1)) {
    // Do some error handling.
    document.write('something went wrong!');
  }
}

Here is an example of this on code pen

Note the use of parseInt above to handle, null, '' and other text values. Invalid numbers will be parsed to NaN which will fail to meet the condition.

mleonard87
  • 324
  • 1
  • 11
-2

If you are using lodash, you can use

_.pluck(window, function(key, value) {}) and then check if key contains variable name and value is less than 10.

Ankit Tanna
  • 1,779
  • 8
  • 32
  • 59
-2

You can use

var i;
for (i = 0; i <= 10; i=i) { // i=i means do nothing
   i++;
   if( eval("score" + i + ">=0 && score" + i + "<=1") ) {
      // do something
   }
}

However, you should use some sort of type-checking; eval is considered unsafe in certain contexts.

  • Mine does not require seperate variables; the OP asked to do it in seperate vars, I do not know why so many answers are not like this. – Parentheses Nov 15 '16 at 22:43
  • I didn't downvote, but many programmers consider `eval` as "evil" due to potential security concerns. Also, why not use `i++` as the third `for` argument instead of putting it within the loop? – Rick Hitchcock Nov 15 '16 at 22:50
  • Loops are hard to loop around my head; there isn't always a "1 to 10" in every programming language. Oh, and I did not know about the evil eval, so that makes sense now. Thanks. – Parentheses Nov 15 '16 at 23:01