Forced conversion rules in js

Foreword

JavaScript There are seven built-in data types, including basic types and object types

 

basic type

The basic types are divided into the following six:

  • string (string)

  • boolean (Boolean value)

  • number (Digital)

  • Symbol (symbol)

  • the null (empty value)

  • undefined (undefined)

  1. string, number, boolean, and null undefined five types collectively referred to as primitive types (Primitive), that they can not be subdivided down basic types

  2. is the symbol ES6 new data type, represents a unique symbol values ​​generated by the Symbol function call, due to the formation of the primitive type value symbol, the new function can not use call Symbol

  3. null and undefined generally considered to be a special value, the value of these two types of unique, is its own

 

Object Types

Object type, also known as reference types, array and function is a sub-type of the object. Objects logically unordered collection of properties, various values ​​of the container is located. The object is a reference value stored in the address, so that different basic types and values ​​immutable characteristic, the value of the object is variable

 

 

Forced conversion rules in js

ToPrimitive (into the original value)

ToPrimitive conversion process does not occur on the original type, only for reference type (object), which is a reference type object (object) into a non-object types, that is, the original type

ToPrimitive operators accept a value, and an optional parameter for the desired type. ToPrimitive operator to convert a non-object type value, if the object has the ability to be converted into more than one type of primitive, the desired type can be used to suggest alternative that type

The result of converting the original type is determined by the desired type, type the desired type of fact it is that we pass. Direct see more clearly below. ToPrimitive method probably long such a way as follows

/ ** 
* @obj need to convert the object 
* @type raw data is converted into the desired Optional 
* / 
ToPrimitive (obj, type)

 

Illustrate the different values ​​of type

    • type is string

      1. First call the toString method of obj, if the original value, then return, otherwise step 2

      2. Call valueOf method of obj, if the original value, then return, otherwise step 3

      3. TypeError exception is thrown

    • type for the number

      1. Call valueOf method of obj, if the original value is returned, otherwise step 2 under

      2. toString method calls obj, if the original value, then return, otherwise step 3

      3. TypeError exception is thrown

    • type parameter is null

      1. The object is a Date, the type is set to String

      2. Otherwise, type is set to Number

 

Date data type specific instructions

Date data types, we expect more of the string is converted to its time, rather than milliseconds (time stamp), if Number, it will take a value corresponding to a millisecond, the string using more clearly. Other types of objects according to the type of operation to the value

 

ToPrimitive summary 

 ToPrimitive converted into original type which, depending on type, type an optional parameter, if specified, the specified type conversion, if not specified, the default two conditions according to the practical situation, Date of string, the remaining objects as a number. So when it specifies the type type, it depends on the way following the two conversion

 

 

Object.prototype.toString()

toString () method returns a string representing the object

Each object has a toString () method, when the target value is represented as a text string or when the desired reference objects, the method is automatically invoked

Here to remember, valueOf () and toString () will call itself in a particular situation

 

 

Object.prototype.valueOf () method returns the value of the specified object's original

JavaScript call valueOf () method is used to convert an object into a value (numeric, string, and Boolean) primitive type. But we rarely need to call this function yourself, valueOf method is usually invoked automatically JavaScript

valueOf different built-in objects to achieve

  • String => Returns a string value

  • Number => return numeric values

  • Date => returns a number, i.e. the time value, the content of the string is dependent on the specific implementation

  • Boolean => Boolean return value of this

  • Object => return this

Code control

const str = newString('123');
console.log(str.valueOf());//123
​
const num = newNumber(123);
console.log(num.valueOf());//123
​
const date = newDate();
console.log(date.valueOf()); //1526990889729
​
const bool = newBoolean('123');
console.log(bool.valueOf());//true
​
const obj = newObject({valueOf:()=>{
    return1
}})
console.log(obj.valueOf());//1

 

 

Number

Number Operator conversion rule

  • null converted to 0

  • undefined is converted to NaN

  • true is converted to 1, false converted to 0

  • Convert a string to follow the rules when numeric constants, conversion failed return NaN

Here the object must first be converted to the original value, calling ToPrimitive conversion, type specified as a number, and continue to return ToPrimitive conversion (see ToPrimitive)

 

 

String

String operators conversion rule

  • null is converted to 'null'

  • convert undefined undefined

  • converts true 'true', false converted to 'false'

  • Digital converter to follow a general rule, use index Maximin digital form

Here the object must first be converted to the original value, calling ToPrimitive conversion, type the designation as a string, and continue to return ToPrimitive conversion (see ToPrimitive)

String(null)                 // 'null'
String(undefined)            // 'undefined'
String(true)                 // 'true'
String(1)                    // '1'
String(-1)                   // '-1'
String(0)                    // '0'
String(-0)                   // '0'
String(Math.pow(1000,10))    // '1e+30'
String(Infinity)             // 'Infinity'
String(-Infinity)            // '-Infinity'
String({})                   // '[object Object]'
String([1,[2,3]])            // '1,2,3'
String(['koala',1])          //koala,1
Boolean(undefined) // false
Boolean(null) // false
Boolean(0) // false
Boolean(NaN) // false
Boolean('') // false
Boolean({}) // true
Boolean([]) // true
Boolean(newBoolean(false)) // true

 

 

Boolean

Operators conversion rule ToBoolean

In addition to the conversion result values ​​below 6 is false, true of all other

  1. undefined

  2. null

  3. -0

  4. 0 or +0

  5. NaN

  6. '' (The empty string)

False values ​​are values ​​other than the true value. This includes all objects (including an empty object) conversion result is true, even false Boolean object corresponding to the new Boolean (false) is true

Boolean(undefined) // false
Boolean(null) // false
Boolean(0) // false
Boolean(NaN) // false
Boolean('') // false
Boolean({}) // true
Boolean([]) // true
Boolean(newBoolean(false)) // true

 

 

js conversion rules apply in different scenarios

What time is automatically converted to string type

Under the premise of no object

Automatic string conversion mainly occurs when adding a string. When a string value, the other value is not a string, the string into the latter

'2' + 1// '21'
'2' + true// "2true"
'2' + false// "2false"
'2' + undefined// "2undefined"
'2' + null// "2null"

When there is an object, and when the object +

// toString object 
var obj2 = { 
    toString: function () { 
        return'a ' 
    } 
} 
the console.log (' 2 '+ obj2) 
// output. 2A 
// general object 
var OBJ1 = { 
   A:. 1, 
   B : 2 
} 
the console.log ( '2' + OBJ1); 
// output 2 [Object Object] 
// several special objects 
'2' + {} // "2 [Object Object]" 
'2' + [ ] // "2" 
'2' + function () {} // "2function () {}" 
'2' + [ 'Koala',. 1] // 2koala,. 1

Of the above '2' + obj2 illustrated in detail as follows

  1. Left for the string, does not change the original value after conversion ToPrimitive

  2. Also in accordance with the original value ToPrimitive for conversion conversion to the right, because the specified type is Number, calls for conversion ToPrimitive obj2.valueof (), the original value is not obtained, the third step

  3. Call toString () return 'a'

  4. Symbol string exists on both sides, but the + operator uses the String rules are converted to a string type splicing

  5. The output 2a

Of the above '2' + obj1 illustrated in detail as follows

  1. Does not change after left for the string, ToPrimitive into the original value

  2. Also in accordance with the original value ToPrimitive for conversion conversion to the right, because the specified type is Number, calls for conversion ToPrimitive obj2.valueof (), to give {a: 1, b: 2

  3. Call toString () return [object Object]

  4. Symbol string exists on both sides, but the + operator uses the String rules are converted to a string type splicing

  5. Output 2 [object Object]

Several special conversion rule object code is basically the same, not setting them, you can think about the process

Whether the object is not an object, there is a process of converting the original value, that is ToPrimitive conversion, but does not change the original type conversion, object type specific conversion will occur

  

string type conversion development process often wrong point

var obj = {
  width: '100'
};
​
obj.width + 20// "10020"

Expected outputs an actual output result 120 10020

 

 

When automatically converted to Number type

  • There addition operator, but without String type, the type will be preferentially converted to Number

    true+0// 1
    true+true// 2
    true+false//1
  • In addition to the addition operator, other operators are automatically converted into the numeric calculation

    '. 5' - '2'. 3 // 
    '. 5' * '2' // 10 
    to true - // 0. 1 
    to false - // -1. 1 
    '. 1' -. 1 // 0 
    '. 5' * [] // 0 
    to false / '. 5' // 0 
    'ABC' - NaN3. 1 // 
    null +. 1. 1 // 
    undefined + NaN3. 1 // 
    // unary (note point) 
    + 'ABC' // NaN3 
    -'abc '/ / NaN3 
    +. 1 to true // 
    -false // 0
    

    When converted to null value is 0, while a value of undefined Switch NaN

     

 

 

Analyzing the equal sign is also placed inside special instructions Number

Abstract is equal to + == Comparison operators different priority String is longer, but Nuber priority. Examples of x == y listed below

  • If x, y are the number, no direct comparison of the interpretable

    1 == 2 //false
  • If the object exists, ToPrimitive () type converted to number, then later comparison

    OBJ1 = {var 
        valueOf: function () { 
            return'1 ' 
        } 
    } 
    1 == OBJ1 to true // 
    // OBJ1 into the original value, calling obj1.valueOf () 
    // returns the original value of' 1 ' 
    //' 1 ' toNumber == 1 then compared to give a 1 
    [] ==! [] to true // 
    // [] to give a target ToPrimitive ' 
    //! [] as converted boolean 0 
    //' '== 0 
    // convert 0 == 0 // true
  • In boolean, according to the boolean ToNumber converted to 1 or 0, and then later comparison

    // boolean first converted to number, obtained in accordance with the above rules 1 
    // == 1. 3 to false 
    // 0 == 0 to true 
    . 3 to true // to false == 
    '0' == // to false to true
  • If x is a string, y is a number, number compared to turn x

    // '0' toNumber () to give 0 
    // 0 == 0 to true 
    '0' to true // == 0
    

     

 

When Boolean conversion

  • Boolean comparison

  • if (obj), the time while (obj) is determined, or the like can only contain ternary operator Boolean

Each value corresponds to the condition part are false, the negation operator after use, it becomes a true

IF (! undefined 
  && null! 
  && 0! 
  && NaN3! 
  && '!' 
) { 
  the console.log ( 'to true'); 
} // to true 
// following two cases may be transferred to a boolean type 
expression true: false? 
!! expression

 

 

NaN related summary

NaN concept

NaN is a global property of the object, NaN is a global property of the object, NaN is a special type Number

When return NaN (second opening questions were resolved)

  • Infinity divided by infinity

  • To do any negative square root

  • Arithmetic operators used in conjunction with a number or not can not be converted into a digital operands

  • Parse the string into a digital

Some examples

Infinity / Infinity; // infinity divided by infinity 
Math.sqrt (-1); // make square root for any negative 
'a' - 1; // arithmetic operators together with a number or not can not be converted into a digital operands using the 
'A' *. 1; 
'A' /. 1; 
the parseInt ( 'A'); // parse the string into digital 
parseFloat ( 'A'); 
number The ( 'A'); // NaN3 
'ABC' -. 1 NaN3 // 
undefined + NaN3. 1 // 
// unary (note point) 
+ 'ABC' // NaN3 
-'abc '// NaN3

 

 

Misunderstanding

String toString and the difference

 

  • toString () data may be converted to a string, but can not convert null and undefined

    console.log(null.toString())
    //报错 TypeError: Cannot read property 'toString' of null

    console.log(undefined.toString())
    //报错 TypeError: Cannot read property 'toString' of undefined
  • String

    String () may be converted to a string null and undefined, but can not turn hexadecimal string

    console.log(String(null));
    // null
    console.log(String(undefined));
    // undefine
  • toString () can write numbers in brackets, on behalf of hexadecimal

    • Binary: .toString (2)

    • Octal: .toString (8)

    • Decimal: .toString (10)

    • Hex: .toString (16)

 

Guess you like

Origin www.cnblogs.com/zhazhanitian/p/12599252.html