The following function uses a Short Circuit Operator to return 0 as default:
function custNumParse(str){
return str*1||0;
}
I am not sure when this will return the second (I mean, I know that it will when str*1 can’t be evaluated to true), but I am not sure what inputs could produce that output when multiplying by 1.
I know that the falsish values are 0, "", false, null, undefined, NaN, but this doesn’t help me that much.
In other words I am clueless what would happen when I use that function with objects or booleans, etc. I know I can test them all, but I am sure there is an easier way to go
Any ideas on what is the most proper way to find these guys without testing them all?
The
*operator is only for numbers, so anything that’s not a number (or can’t be converted to one) will makestr*1returnNaN. Also0*1is obviously0.EDIT: booleans seems to be converted to either
0or1.EDIT 2: Strings with numeric values will also be converted
EDIT 3: Be careful with arrays (they are converted to strings and then to ints).