admin管理员组文章数量:1421761
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?
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?
Share Improve this question asked Nov 15, 2016 at 22:32 user45867user45867 9832 gold badges18 silver badges37 bronze badges 1-
6
Put your scores in array then you can use a
for
loop to check each one. – Mike Cluck Commented Nov 15, 2016 at 22:32
9 Answers
Reset to default 9Just 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);
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
}
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.
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/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/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
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.
const scores = [0.1, 0.2, 0.3, 0.4, 1, 2, 3, 4, 5, 6];
scores.forEach(function(score){
// http://stackoverflow./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!");
});
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.
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.
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.
本文标签: Javascriptquick way to check if 10 variables are between 0 and 1Stack Overflow
版权声明:本文标题:Javascript - quick way to check if 10 variables are between 0 and 1? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745351267a2654781.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论