In strong-type languages such as C/C ++ and C #, forced conversion of variable types is quite common. However, JavaScript, a variable of the dynamic scripting language, claims to be of no type. How can we convert its variable type? It also needs to be forcibly transferred.
Javascript variables do not have a type. That is to say, after var variable, you can assign a value to variable without any problems. However, the value assigned to the variable itself has a type, such as string, object, Boolean, and number. Therefore, JS variables still have type conversion. Of course, many JS parsing engines process a lot of Type Convert by default. However, sometimes we also need to forcibly convert the data type, the most common is: ''+ number, in this case to generate string accumulation.
For example: ''+ number, this syntax is really quite uugly. We want to use (INT) XXX in C and INT (XXX) in C ++) it is clear how to convert data types. In fact, JavaScript also supports such type conversion syntax, such:
< Script Language = "JavaScript" >
VaR Str = ' 100 ';
VaR Num = Number ( 100 );
Alert ( Typeof (Num) + ':' + Num );
VaR OBJ = Object (STR );
Alert ( Typeof (OBJ) + ':' + OBJ );
VaR Bool = Boolean (STR );
Alert ( Typeof (Bool) + ':' + Bool );
VaR Num = 100 ;
VaR Str = String (Num );
Alert ( Typeof (STR) + ':' + Str );
VaR Bool = Boolean (Num );
Alert ( Typeof (Bool) + ':' + Bool );
VaR OBJ = Object (Num );
Alert ( Typeof (OBJ) + ':' + OBJ );
VaR Bool = True ;
VaR Str = String (bool );
Alert ( Typeof (STR) + ':' + Str );
VaR Num = Number (bool );
Alert ( Typeof (Num) + ':' + Num );
VaR OBJ = Object (bool );
Alert ( Typeof (OBJ) + ':' + OBJ );
VaR OBJ = {} ;
VaR Str = String (OBJ );
Alert ( Typeof (STR) + ':' + Str );
VaR Num = Number (OBJ );
Alert ( Typeof (Num) + ':' + Num );
VaR Bool = Boolean (OBJ );
Alert ( Typeof (Bool) + ':' + Bool );
</ Script >
In addition to the number (OBJ) Conversion failure, other forced conversion expressions can achieve meaningful conversion effects.
The biggest advantage of using a forced conversion expression is thatProgramCodeIt becomes clearer, reducing the possibility of obfuscation for JavaScript programming that is inherently type-confusing.
at least I think var STR = string (3) + String (3); clearer than VaR STR = ''+ 3 + 3.
the default conversion is messy, for example, "88"-8 "and" 88 "+ 8. The default conversion of the former is to convert the string to a number (result 80 ), the latter converts numbers into strings (result "888") @ _ @, which is really messy. Therefore, forced conversion of variable types may avoid potential understanding errors caused by such default conversions.