I am not a JavaScript developer ,but I just want to know the right way to check a variable contain a number or not . After a couple analysis I reached below solution . Is it correct way , please provide your thoughts.
function calculation(n1,n2 , ...numbers) {
let validateNumber = (num) => {
if(num !== num)
return 0;
else
return typeof num === 'number' ? num : 0;
}
let sum =0;
for(n of numbers){
sum = validateNumber(n);
}
console.log(sum);
}
calculation(5,6,7,'gg','',null, NaN, undefined, null,8,9,5.4,10);
Please check the 'validateNumber' arrow function.
Thank you.
CodePudding user response:
simply use isNaN()
const calculation = (n1,n2,...numbers) => numbers.reduce((sum,val)=>sum (isNaN(val)?0:Number(val)), 0)
console.log( calculation(5,6,7,'gg','',null, NaN, undefined, null,8,9,5.4,10) )
CodePudding user response:
Yes, there is built in function in JavaScript to check if a certain value is number or not which is isNaN()
If you want to get the sum of all the numbers in the array then you can try using reduce()
like the following way:
var data = [5,6,7,'gg','',null, NaN, undefined, null,8,9,5.4,10];
var sum = data.reduce((a,c) =>{
if(!isNaN(c)){
a = a Number(c);
}
return a;
},0);
console.log(sum)
CodePudding user response:
Yes it is a one liner also
export const isNum = n => Number(n) === Number(n);
First parse to number what Eva param you get them compare to itself.
One of them what the hell's
that comes with JavaScript is that NaN !== NaN
so if the value you get after forcing it to be a number become s a Nan it will be different from itself
CodePudding user response:
You can filter
out the elements that aren't numbers by checking to see if they're not null
and also a number, and then using reduce
to sum up the elements.
function calculation(n1, n2, ...elements) {
return elements
// `filter` out the elements that are numbers
.filter(el => el && Number(el))
// Add them all up
.reduce((acc, c) => acc c, 0);
}
console.log(calculation(5,6,7,'gg','',null, NaN, undefined, null,8,9,5.4,10));