I originally wrote this code to be preventing input field to submit value lesser than 0:
if (
inflationArray[2].value < 0 ||
inflationArray[1].value < 0 ||
inflationArray[0].value < 0
) {
alert("Can't input negative value");
return;
}
And it didn’t look like the best possible way to do it so I tried replacing it with this piece of code:
if (inflationArray.map((x) => x.value < 0)) {
alert("Can't input negative value");
}
Why is it not the same, did I not understand .map() correctly?
My only conclusion is that it might be because that the second way I wrote is not equal to the first one (If I am correct), but:
if (
inflationArray[2].value < 0 &&
inflationArray[1].value < 0 &&
inflationArray[0].value < 0
) {
alert("Can't input negative value");
return;
}
>Solution :
You’re looking for either Array.prototype.every() or Array.prototype.some().
This will test that every array-element has a value greater than zero, and return true if so (or false if not):
inflationArray.every((value) => value > 0);
Or, this can test that any of the array-elements hold a value of less-than zero; and return true if any one, or more, does (false if none are below zero):
inflationArray.some((value) => value < 0);
References: