I am trying to check all the element type of an array in javascript. I am actually writing a function which whould only accept an array with numbers.
so
[1,2,-3,-4,0] //valid input
[1,2,-3b,-4a,0] //Invalid input
I am trying to achieve the following by using every() function of javascript as follows,
try {
if (!inputArr.every(x => typeof x === 'number')) {
throw 'input array should only have numbers';
}
}
catch (err) {
return err;
}
but getting error. when I investigate it further than realized that,
typeof 1 // number
typeof 1a // error
so there is no way we can check the type of a alphanumeric value. can someone please suggest some options here. I am using pure javascript ES5 Or ES6.
isNaN("123")would returnfalse, even though"123"is not a number. If that suits OP's needs, then it would work. If the goal is a stricter check, thentypeofseems like the way to go.[1,2,-3b,-4a,0]is invalid syntax, and your program would not even run, should we assume that the input is a kind-of array represented as a string, as in"[1,2,-3b,-4a,0]"?"[1,2,-3a,4]"? That is a whole different question. I would first useJSON.parse()to attempt to convert this string to a JavaScript array. If it throws an exception, then you had something like the "-3a" in it and should reject. Otherwise, run your test loop on the resulting array.