Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - How to convert the type of JS
How to convert the type of JS
What I brought to you this time is how to convert JS types, and what are the precautions for JS type conversion. Here is an actual case, let's take a look.

Implicit type conversion

In JavaScript, when we compare, add, subtract, multiply and divide, we often trigger the implicit type conversion mechanism of JavaScript. And this part is often confusing. For example, the console.log operation in the browser is often displayed after converting any value into a string, while the mathematical operation is to convert the value into a numerical type (except for date type objects) before the operation.

Let's first look at the typical operator operation results in several groups of JavaScript, hoping that after reading this section, each item can be reasonably explained:

//comparison

+ // '2,3 1,2'

-1/south

{} - 1 // - 1

Conversion between primitive types

The primitive types we often say in JavaScript include numeric type, string type, Boolean type and empty type. The conversion functions between primitive types we often use are string, number and Boolean:

//String

Set value = true.

Console.log (type of value); //Boolean type

Value = String (value); //Now the value is the string "true"

Console.log (type of value); //String

//Numbers

let str = " 123 ";

Console.log (string type); //String

Let num = number (str); //becomes a number 123

Console.log (type number); //Numbers

Let age = Number ("any string instead of a number");

Console.log (age); // NaN, conversion failed.

//Boolean type

console . log(Boolean( 1)); //true

console . log(Boolean(0)); //False

console . log(Boolean(" hello ")); //true

console . log(Boolean(" "); //False

Finally, we can get the following JavaScript primitive type conversion table (including examples of conversion from composite types to primitive types):

original value

Convert to numeric type

Convert to string type

Convert to Boolean type

wrong

"false"

wrong

real

1

"Truth"

real

"0"

wrong

1

1

" 1"

real

"0"

"0"

real

" 1"

1

" 1"

real

Disc scone

Disc scone

"South"

wrong

infinite

infinite

"Infinite"

real

-Infinite

-Infinite

"-Infinite"

real

""

""

wrong

"20"

20

"20"

real

"twenty"

Disc scone

"twenty"

real

Disc scone

" 10,20"

real

["Twenty"]

Disc scone

"twenty"

real

【 "Ten" and "Twenty" 】

Disc scone

Ten, twenty

real

Function () {

Disc scone

"Function () {}"

real

{ }

Disc scone

"[Object Object]"

real

empty

"Empty"

wrong

ambiguous

Disc scone

"Undefined"

wrong

primitive

In comparison operation and addition operation, it will involve the steps of transforming the manipulated objects on both sides of the operator into the original objects. However, this transformation in JavaScript is actually performed by the ToPrimitive function. In fact, when an object appears in a context that requires the operation of the original type, JavaScript will automatically call the ToPrimitive function to convert the object into the original type; For example, the above-mentioned alert function, mathematical operator and key as objects are typical scenarios, and the signature of this function is as follows:

ToPrimitive(input,PreferredType? )

To better understand how it works, we can simply implement it in JavaScript:

var ToPrimitive = function(obj,preferredType){

var APIs = {

Type Of: function (object) {

Returns object.prototype.tostring.call (obj). slice(8,- 1);

},

isPrimitive: function(obj){

var _this = this,

types = ['Null ',' Undefined ',' String ',' Boolean ',' Number '];

! returns types.indexOf(_this.typeOf(obj))! == - 1;

}

};

//If the obj itself is already the original object, return it directly.

if(APIs . is primitive(obj)){ return obj; }

//For date type, its toString method will be used first; Otherwise, the valueOf method is preferred.

preferred type =(preferred type = = = ' String ' | | APIs . type of(obj)= = = ' Date ')? String':' Number';

if(preferredType==='Number'){

if(APIs . is primitive(obj . value of()){ return obj . value of()};

if(APIs . is primitive(obj . tostring()){ return obj . tostring()};

} Otherwise {

if(APIs . is primitive(obj . tostring()){ return obj . tostring()};

if(APIs . is primitive(obj . value of()){ return obj . value of()};

}

Throws a new typeerror ('typeerror');

}

We can simply override the valueOf method of an object, that is, we can find that its operation result has changed:

Let obj = {

value of:()= & gt; {

Returns 0;

}

}

obj + 1 // 1

If we force the valueOf and toString methods of an object to be rewritten as methods that return the value of the object, an exception will be thrown directly.

obj = {

ValueOf: function () {

console . log(" value of ");

return { }; //is not a primitive

},

toString: function () {

console . log(" toString ");

return { }; //is not a primitive

}

}

obj + 1

//Error

Type error not captured: Cannot convert object to original value.

At< anonymous & gt: 1:5

It is worth mentioning that the result of calling the valueOf () function of numeric type is still an array, so the result of implicit type conversion of array type is a string. After the symbol type is introduced into ES6, JavaScript will first call the [Symbol. top primitive] method of an object to convert the object into the original type, so the calling order of the method becomes:

When obj[ symbol. The topprimal] (preferred type) method exists, which is called first;

If the preferredType parameter is String, try obj.toString () and obj.valueof () in turn; If the preferredType parameter is Number or the default value, try obj.valueOf () and obj.toString () first.

And the signature of the [[symbol. topriminal] method is:

obj[symbol . top primitive]= function(hint){

//Returns the original value

// hint = one of string, number and default value.

}

We can also modify the operational performance of the object by overriding this method:

User = {

Name: "John"

Money: 1000,

[symbol. top primitive] (prompt) {

console . log(` hint:$ { hint } `);

return hint == "string "? `{ name:" $ { this . name } " } `:this . money;

}

};

//transformation demonstration:

Console.log (user); //Tip: string-& gt;; {Name: "John"}

Console. log(+ user); //Hint: $ number-& gt;; 1000

Console.log (user+500); //Tip: Default-> 1500

Comparison operation

JavaScript provides us with two modes: strict comparison and type conversion comparison. Strict comparison (= = =) will only return true if the operand types and contents on both sides of the operator are consistent, otherwise it will return false. The more widely used = = operator first converts operands to the same type and then compares them. for

Standard equality operators (= = and! =) The abstract equality comparison algorithm is used to compare the operands on both sides of the operator (x == y), and the key points of the algorithm flow are extracted as follows:

If one of x or y is NaN, it returns false;;

Returns true (null = = undefined//true) if both x and y are empty or undefined; Otherwise return false (null = = 0//false); If the types of X and Y are inconsistent, and X and Y are one of string, number and Boolean, use the to Number function to convert X and Y into number types, and then compare them; If one of X and Y is an object, first convert it to the original type with the ToPrimitive function, and then compare it.

Let's review the [] = = proposed at the beginning of the following! [] This comparison operation, first [] is an object, and then the ToPrimitive function is called to convert it into a string ""; For the right! [], which will first be converted to false by explicit type conversion. Then in the comparison operation, the operands on both sides of the operator will be converted to numeric types, that is, they will all be converted to 0, so the final comparison result is true. Null > = 0 is true, and ECMAScript also stipulates that if = is true.

Add operation

For addition, JavaScript will first convert the objects on both sides of the operator into primitive types; Then, when proper implicit type conversion can get meaningful values, JavaScript will perform implicit type conversion first, and then perform operations. For example, the expression value 1+value2 will first call the ToPrimitive function to convert two operands to their original types:

Prim 1:= top primitive (value 1)

Prim 2:= top primitive (value 2)

The valueOf method of objects other than date type will be called first, because the return valueOf the valueof method of array is still array type, so its string representation will be returned. However, if any one of the converted prim 1 and prim2 is a string, string concatenation is preferred; Otherwise, carry out addition calculation.

I believe you have mastered the method after reading this case. For more exciting, please pay attention to other related articles on Gxl!

Recommended reading: