Javascript method for converting operations between different types of data

  • 2020-03-30 01:42:04
  • OfStack

The basic data in js can be converted between different types. This conversion is regular and searchable, not random. There are five basic types of data in js: string, number, Boolean, null, and undefined.

Conversion between underlying data

Other types convert Numbers Raw data type Target type Number undefined NaN null 0 false 0 True, 1 The Numbers Corresponding number String that cannot be converted NaN Other types are converted to strings Raw data type Target type String undefined undefined null null false false True, True, digital Numeric string

 

Addition between different types of basic data, which is converted to number first, and then to string(if string type data is involved)


null + undefined // 0+NaN 

null + false // 0+0 

1 + true // 1+1 

1 + '1' //'11'; The result is a string when a number is added to a string

1 + 2 + '3'  //'33'; The sum of 1 plus 2 plus 3 prime; I'm going to break each of these up separately, otherwise it's going to look like this.

1 + (2 +'3') //'123'. 2+'3', and then 1+'23'.

's' + null //'snull' 

's' + undefined // 'sundefined' 

's' + true //'strue' 

1 + true + undefined + 's' // 1+1+NaN+'s'=2+NaN+'s'=NaN+'s'=NaNs 

Object participates in the addition and subtraction operation

Object to participate in the base type data operation, first converted to the base type. Its valueOf method is called first, then its toString method is called if the underlying type is not returned, and an error is thrown if the underlying type is not returned. However, Date data does the opposite


//To make it easy to observe the toString and valueOf methods that override Date

Date.prototype.toString = function(){ 
    return 1; 
} 

Date.prototype.valueOf = function(){ 

    return 2; 
} 

var a = new Date, 
    b = new Date; 

a + b; //Call toString, 1 + 1, and it's 2

//Rewrite the toString method

Date.prototype.toString = function(){ 

    return {}; 
} 

var c = new Date, 
    d = new Date; 

c + d; //Instead of returning the underlying type, call the toString method, and call valueOf, 2 + 2, and the result is 4

//Override the valueOf method again
Date.prototype.valueOf = function(){ 

    return {}; 
} 

var e = new Date, 
    f = new Date; 

e + f; //  An error  

Changing the above example to Object or some other type will give you the result, but only by calling valueOf first and then toString.

The magic of the '+' sign

The data is preceded by a plus sign '+', which converts the string to a number


+'1'+1 // 2 

+'s'+2 // NaN 

Note: the first time, the format is not good, the flaw is more, welcome everyone clap brick


Related articles: