var New String ("abc"); Console.log (typeof// is an object, not a string
Use the new String ("abc"); The wrapper object for string ABC is created instead of the base type value "ABC".
Encapsulating objects
Because the base type value does not have. Length and. ToString () Properties and methods that need to be accessed by encapsulating an object, JavaScript automatically wraps an encapsulated object for the base type value, such as:
var a = "abc"; Console.log (a.length);
Note: If you need to use the. Length property and methods frequently, it may be easier to create a wrapper object from the outset, but it is important to note that this is not the case because the browser has optimized performance for these common methods. The direct use of encapsulated objects to optimize in advance, but will reduce the efficiency of execution.
var New Boolean (false); if (! a) { console.log (// will never be executed here }
Create a encapsulated object for false, however the object is really truthy, all always returns True, and if you want to encapsulate the base type value yourself, you can use the object function.
Unopened
If you want to get the underlying type values in the encapsulated object, you can use the valueof function:
var New String ("abc"); Console.log (a.valueof ()); // ABC
Dates Date
The creation Date object must use the new date () date to specify the date and time without parameters, using the current date and time.
Force type Reload
Forcing type conversions is divided into implicit conversions and display transformations, and the difference between these two conversions is defined by the way you understand the program. For example:
var a =$var b = A + ""; // Implicit conversions var c = String (a); // Show Transformations
If you understand A + "", then this line of code is also an explicit conversion for you.
ToString Method
The basic type of the string rule is: null is converted to "null", undefined conversion to "undefined" true is converted to "true", the number of the string is the most common rules required.
For a normal object, ToString returns the value of the internal property class, unless defined by itself, such as: [Object Object]
JSON string
Json.stringify is automatically ignored when it encounters undefined, function, and symbol in an object.
Replacer
We can pass an optional parameter replacer to the Json.stringify method, which can be an array or a function that specifies the object sequence number during which those attributes should be handled or excluded, and if Replacer is an array, it must be an array of strings
The property name that contains the serialized object to be processed is ignored.
If Replacer is a function, it is called once for the object itself, and then once for each property of the object, passing two arguments, building and values each time, and returning undefined if a key is omitted, otherwise the specified value is returned.
For example:
// {"B": "A", "C": "*"} function // {"B": "D": [[+]} if (k! = "C") {return v; }}) ;
Tonumber
The Tonumber method, where true translates to 1,false to 0,undefined conversion to Nan,null to 0
At the time of conversion, first check if there is a valueof method, and if it has and returns a base type value, use that value to force the type conversion, if not the return value of ToString is used to force the type conversion. If both valueof and ToString do not return a base type value, a typeerror error is generated. (The object property created with Object.crete (NULL) is NULL, and there are no two methods)
varA ={valueOf:function () { return"43"; } } varb ={toString:function () { return"43"; } } varc = [4, 3]; C.tostring=function () { return This. Join (""); } console.log (Number (a)); // +Console.log (number (b));// +Console.log (number (c));// +Console.log (Number (""));//0Console.log (number ([]));//0Console.log (Number (["ABC"]));//NaN
ToBoolean
We often mistakenly believe that values 1 and 0 are equal to true and false, which may be the case in some languages, but the Boolean and number are different in JavaScript, although we can cast 1 to true,0 to false and vice versa, but they are not the same thing.
These are the values that can be converted to false:
Undefined
Null
False
+0,-0, NaN
""
We can understand that except for the above conversion to false values, the other is the truth
For example:
varA = "false"; varb = "0"; varc = "'"varD = []; varE = {}; varf =function () { }; Console.log (Boolean (a)); //trueConsole.log (Boolean (b));//trueConsole.log (Boolean (c));//trueConsole.log (Boolean (d));//trueConsole.log (Boolean (e));//trueConsole.log (Boolean (f));//true
The truth value can be infinitely long, so cannot be enumerated, here can only be used as a list of false values for reference.
Explicit cast + operator
var a = "3.14"; Console.log (+a); // 3.14
Convert directly to numeric type instead of digital wig operation, nor string concatenation.
var a = "3.14"; var d = 5 + +A;console.log (+d); // 8.14
It is important to note that there are two + number problems, and if you do not add spaces to the middle, you may be able to follow the + + self-increment operation.
var New Date (); Console.log (//1482134335608var d = +new// 1482134335609
The date is converted directly to the number of milliseconds.
However, this kind of writing may not be very good in readability, and it is not recommended to use casts to get the number of milliseconds, so there are several ways to get the number of milliseconds:
vartimestamp =NewDate (). GetTime (); Console.log (timestamp);//1482134515222 varTimestamp = (NewDate ()). GetTime (); Console.log (timestamp);//1482134515222 varTimestamp = (NewDate). GetTime (); Console.log (timestamp);//1482134515222 vartimestamp =Date.now (); Console.log (timestamp);//1482134515222 recommend this notation
~ operator
~ indicates a word-bit operation "not" related to firearm conversion.
~x is roughly equivalent to-(x+1). For example:
Console.log (~42); // -43
It is important to note that in-(x+1) the only X value that can be 0 is 1, and the 1 is a slight value, which is the value given a special meaning. The program generally uses a value greater than or equal to 0 to indicate success, and 1 indicates failure. For example, the IndexOf method.
Then this >=0 or ==-1 is not very good, and this code is called "abstract leakage", meaning that the underlying implementation details are exposed in the code. This refers to the value returned with 1 as the failure, and these details should be masked out.
For example:
var a = "Hello"; if (~a.indexof ("Lo")) { Console.log ("true"); } if (!~a.indexof ("Li")) { Console.log ("false"); }
Using this method is more concise than >=0.
~ ~ Word bit truncation
// -50 // -49 higher priority // -49 Low priority
Parsing numeric strings
The difference between the number () and the parseint () methods:
var a = "a"; var b = "42px"; // the Console.log (parseint (a)); // the // NaN Console.log (parseint (b)); // the
You can see that the parseint method stops the conversion when it executes to a character that is not non-convertible to a number, and then returns the previous value, while the number method requires that the whole must be convertible before it returns, otherwise Nan is returned.
parseint Method Execution Process:
var a = { function () { return '; } } Console.log (parseint (a)); // -
As you can see, the parseint method first converts the argument to a string and then parses it.
!! Boolean conversions
var a = 0; Console.log (!! a); // false
Implicit cast + operator
When there are strings on the left and right sides of the + operator, strings are concatenated, otherwise an addition operation is performed. This is generally the case, but there is another situation:
var a = [1, 2]; var b = [3, 4]; + b); // 1,23,4
Both A and B are not strings, so why do they join here because the valueof method of the array is called first, whereas the valueof operation of the array does not get a simple basic type, so instead calls the ToString method, which returns two strings and then stitching.
A A-seat difference between A + "" and a string needs to be noted that A + "" will call the ValueOf method and then convert to a string via ToString, and the string method will call the ToString method directly.
var a = { functionreturn ) ,functionreturn 4} } + ""); // the Console.log (String (a)); // 4
|| and &&
In JavaScript, they are called selector operators more appropriately. Because unlike other languages, they do not return a Boolean value.
They return one (and only one) of the two operands, for example:
var a =; var b = "abc"; var NULL ; // the // the // the // NULL
As you can see, they return one of the two operands, not the Boolean value.
Can be understood in a different way:
a| | B can be understood as:
A?a:b
A&&b can be understood as:
a?b:a;
The following is a common usage:
a=a| | Hello
There is another method that is not common and is commonly found in compression tools, namely:
var a=43; a&&foo ();
This is called a short-circuit, which means that only a is defined to execute the Foo method.
When they are used in the IF, they are actually forced by the if to the final result of the type conversion. Such as:
var a =; var b = "abc"; if (A && b) { Console.log (true//true }
Also equivalent to:
var a =; var b = "abc"; if (!! A &&!! b) { Console.log (true//true }
= = and = = = Operators
Our common explanation for these differences is that = = = checks whether the values are equal, and = = = checks whether the values and types are equal.
This explanation is not accurate and comprehensive and is correctly interpreted as: = = allows coercion of type conversions in equal comparison, while = = = is not allowed.
According to the first explanation, we can enumerate as = = = do more than = =, because it also checks the type, and the second is just the opposite.
= = When you compare values of two different classes, an implicit cast occurs, and one or both of them are converted to the same type before being compared.
For example:
var a =; var b = "a"; // true Console.log (A = = B); // false
So whether to convert a string to a numeric value or a numeric value to a string, the exact conversion rules are as follows:
If type (x) is a number, type (y) is a string, then the result of X==tonumber (y) is returned
If type (x) is a string, type (y) is a number, then the result of Tonumber (x) ==y is returned
= = One of the most error-prone places is a direct comparison of true and false with other types:
var a = "a"; var true ; // false
We all know that "42" is a truth, then why = = The result is not true, look at the specification:
Returns the result of Tonumber (x) ==y if Type (x) is a Boolean type
Returns the result of X==tonumber (y) if Type (Y) is a Boolean type
So here, according to the specification, the true is converted to 1 for comparison, to become "42" ==1, however the type is still different, in the conversion, "42" is converted to 42 into 42==1, so false.
It is recommended that you do not use ==true or ==false whenever you want
In the = = null and undefined is equivalent, that is, only judge ==null can be undefined the situation also judged in.
The most special case:
var i = 2; function () { return i++; } var New Number (a); if (A = = 2 && A = = 3) { Console.log (true); true }
As you can see, the judging condition is true, so it's best not to modify the built-in prototypes.
so = = will inadvertently in the implicit conversion, especially need to pay attention to the two points:
Do not use = = if there is true or false on both sides of the value
If the values on both sides have [], "" or 0 try not to use = =
You should use ongoing=== to avoid these inadvertent errors.
Abstract Relationship comparison
In general, when comparing objects, the object is converted to a string, then the letters are compared, the more common is "123" > "13" is false. However, there are several special cases, such as:
var a = {b:42 }; var b = {b:43 }; // false Console.log (A = = B); // false Console.log (a > B); // false Console.log (a <= b); // true Console.log (a >= b); // true
It is important to note that why A<b and A==b are false, then why is a<=b true?
Because according to the specification, A<=b is processed as a>b and then reverses the result. Because the result of A>b is false, the result of inversion is true.
In fact, JavaScript in the processing of >=, is not greater than the meaning of processing, that is (! A<B)) results.
Native function and mandatory type reload