Вопрос

In JavaScript, variables are loosely typed, so the number 5 and the string "5" may both be treated as a number by several operators. However, is there a generic way to find out JavaScripts conversion abilites in at tunrime, or is it just the overloading of operators for several types that make the loose typing possible?

For example, given a variable a and a string containing a type name type_canditate, is there any way to ask JavaScript, if a may convert to type_candidate in a feasable manner, in contrast to the hard typing operators like instanceof? For example, "5" instanceof Number evaluates false, while Math.sin("5") is perfectly feasable. For numbers, one can obviuosly check if parseFloat(some_number) evaluates to NaN, but this is a special case for numbers.

So, is there any generic way of naming types, and check if some variable may convert to a given type in a useful manner?

Это было полезно?

Решение

There are three primitive data types in JavaScript: string, number and boolean.

Anything can be converted to a string or boolean:

  • All objects convert to true (except null, which becomes false - I only mention it here because typeof null gives object)
  • All objects have a built-in toString method which is called when converting to a string.
  • Converting a number to a string is done by giving the string representation of the number (ie. 5 becomes "5")
  • Numbers convert to boolean true, unless it's 0 which becomes false.

Converting to a number is a little trickier, but technically possible. If it can find a valid number, then it becomes that number. Otherwise, it becomes NaN.

So basically... any type can become any other type through casting in this way. The only time you have anything resembling an "error condition" is NaN.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top