I’m trying to wave out all the bad situations with the elements of my array. But unfortunately my JavaScript code doesn’t work as one piece: it works correctly with a separate "IF" selectors but not all together. Could anybody explain me whats the issue? Thanks a lot in advance!
Here is the code:
/** Check the elements of the array on:
* The array is empty
* Array element/s is/are not a numbers
* Among elements there is not an integers
* Among elements there is a negative number/s
* Among elements there is a too large numbers
*/
const parbaude = (mas) => {
var response = [true, "... No problem found!"];
if (mas.length == 0) {
response = [false, "... Your array is empty!"];
} else if (mas.filter(item => typeof item !== 'number')) {
response = [false, "... Only numbers are allowed!"];
} else if (mas.filter(item => !Number.isInteger(item))) {
response = [false, "... Enter integer only!"];
} else if (Math.min(...mas) <= 0) {
response = [false, "... Only positive numbers are allowed!"];
} else if (Math.max(...mas) > 1000) {
response = [false, "... The number is too large: n < 1000!"];
} else {
// Return the test result
return response;
}
};
// !!! Try each of these options !!!
//const mas = [];
//const mas = [3, 'd', 7, 9];
//const mas = [3, 4.6, 7, 9];
const mas = [3, -4, 7, 9];
//const mas = [3, 4000, 7, 9];
//const mas = [3, 4, 7, 9];
document.getElementById("izvade").innerHTML = parbaude(mas);
2
Answers
Here is the corrected JS:
First, the
return
should not be in theelse
because it will not be processed if one of the above conditions (if
) is met.Second, your condition for number and integer. You should check
every
item in the array if all are met. Move the!
before the statement to indicate the opposite (false
).Lastly, though you can confirm this one. Your condition for negative is
<=0
but0
is not negative so I removed=
. You can keep it though depending on your requirement.Here is the working code: