How does Javascript know what type a variable is?

后端 未结 4 600
遇见更好的自我
遇见更好的自我 2020-12-06 13:52

I don\'t know why I never asked myself that questioned the last years before, but suddenly I could not find any answer for myself or with google.

Javascript is known

4条回答
  •  半阙折子戏
    2020-12-06 14:53

    JavaScript itself does have types, and internally, each assignment receives an appropriate type. In your example var foo = 2.0; the type will be float. The programmer needn't worry about that too much (at first) because JS is loosly typed (!== type-free).
    That means that if I were to compare a numeric string to a float, the engine will coerce the string to a number so that the comparison can be preformed.

    The main difference between loose typed and strong typed languages is not type coercion, though. It's quite common in C(++) to cast to the type you need, and in some cases values are automatically converted to the correct type (2/2.0 == 2.0/2.0 == 1.0 ==> int is converted to float, implicitly). The main difference between loosly typed and strong typed languages is that you declare a variable with a distinct type:

    int i = 0;//ok
    //Later:
    i = 'a';//<-- cannot assign char to int
    

    whereas JS allows you to do:

    var i = 1;//int
    i = 1.123;//float
    i = 'c';//char, or even strings
    i = new Date();//objects
    

    But, as functions/keywords like typeof, instanceof, parseFloat, parseInt,toString... suggest: there are types, they're just a tad more flexible. And variables aren't restricted to a single type.

提交回复
热议问题