Home > Article > Web Front-end > Making the weakly typed language JavaScript strong_javascript tips
Weakly typed Javascript will not convert from the actual variable type to the required data type as the programmer wishes. For example, a very common mistake is to get a user input from a form control in a browser script. The sum of a numeric variable and another numeric variable. Because the variable type in the form control is a string (timed string sequence contains a number) this attempt will add that string to the variable, even if the values happen to be some Number, the result will be converted to string type in the second variable, and in the end, only the variable obtained from the form control will be added to the end of the first string.
So forced type conversion is still relatively important. Let’s take a look at several of its forced conversion functions:
1. Boolean(value): Convert the value to Boolean type;
2. Nnumber(value): Convert the value into a number (integer or floating point number);
3. String(value): Convert the value into a string.
Let’s look at Boolean() first: When the value to be converted is "a string of at least one character", "a non-zero number" or an "object", then Boolean() will return true. If the value to be converted is If it is "empty string", "number 0", "undefined", "null", then Boolean() will return false. You can use the following code to test
var t1 = Boolean("");//Return false, empty string var t2 = Boolean("s");//Return true, non-empty string
var t5 = Boolean(null),t6 = Boolean(undefined);//Return false var t7 = Boolean(new Object());//Return true, object |
以下为引用的内容: var t1 = null; |
The following is the quoted content: Number(false) 0Number(true) 1Number(undefined) NaNNumber(null) 0Number("1.2") 1.2 Number("12") 12Number("1.2.3") NaNNumber(new Object()) NaNNumber(123) 123 | TR>
The following is the quoted content: var t1 = null;var t2 = String(t1);//The value of t2 is "null"var t3 = t1.toString();//An error will be reported herevar t4; var t5 = String(t4);//The value of t5 "undefined |