JS basis - variable type and type conversion

JS variable type

There are six kinds of JS original values, respectively:

  1. boolean
  2. number
  3. string
  4. undefined
  5. symbol
  6. null

Reference types:

  1. Objects
  2. Array
  3. function

JS typeof What types used to get?

One of the strange null, although the basic variables, but because of the design of the nullall-zero, and the object is 000at the beginning, so to have this miscarriage of justice.

  1. boolean
  2. number
  3. string
  4. undefined
  5. symbol
  6. object
  7. function
  8. bigint

What instanceof principle can correctly judge the target is?

Determining whether one object constructor function on a prototype chain

const Person = function() {}
const p1 = new Person()
p1 instanceof Person // true

var str = 'hello world'
str instanceof String // false

var str1 = new String('hello world')
str1 instanceof String // true

Implement a type judgment function

  1. Judgment null
  2. Determine the type of foundation
  3. Used Object.prototype.toString.call(target)to determine the reference type

Note: Be sure to use callto call, or the type of Object.prototype judgment of
reason must first determine whether the basic types because: although Object.prototype.toString.call()can determine a value: number / string / boolean, but in fact, when the packaging is they became the first turn and then determine the type of the object. But JS packaging types and primitive types there are still differences, because of a packaging type, the value is object typeof

/**
 * 类型判断
 */
function getType(target) {
  //先处理最特殊的Null
  if(target === null) {
    return 'null';
  }
  //判断是不是基础类型
  const typeOfT = typeof target
  if(typeOfT !== 'object') {
    return typeOfT;
  }
  //肯定是引用类型了
  const template = {
    "[object Object]": "object",
    "[object Array]" : "array",
    // 一些包装类型
    "[object String]": "object - string",
    "[object Number]": "object - number",
    "[object Boolean]": "object - boolean"
  };
  const typeStr = Object.prototype.toString.call(target);
  return template[typeStr];
}

Turn Boolean

The following are false, all other values ​​are converted to true, including all objects (objects empty, empty array also becomes true).

  • false
  • undfined
  • null
  • ''
  • NaN
  • 0
  • -0

The basic types of objects go

When converting basic types of objects, calls valueOf, calls when needed turn into a character type toString.

var a = {
  valueOf() {
    return 0;
  },
  toString() {
    return '1';
  }
}

1 + a           // 1
'1'.concat(a)   //"11"

It can be rewritten Symbol.toPrimitive, which calls on the turn basic types of the highest priority . Symbol.toPrimitive means converts the attribute values specified function to be called to correspond to the original value.

Type Conversion

Wherein one of a string of calculation, it will be converted to a string to the other
if one is not a string or a number, then converts it into a digital or string

1 + '1' // '11'
true + true // 2
4 + [1,2,3] // "41,2,3"

Also note that this expression'a' + + 'b'

'a' + + 'b' // -> "aNaN"

Because + 'b' is equal to NaN, so the result is "aNaN", you may also be seen in some of the code in the form + '1' to quickly obtain the number types.

JS type conversion rules summary

JS hint type conversion

100 + problem

'100' + 100   // "100100"

100 + '100'   // "100100"

100 + true    // 101

100 + false   // 100

100 + undefined //NaN

100 + null    // 100

"A common string" Why length property

Created by literal manner: var a = 'string' ;, then it is the basic type value; created through the constructor: var a = new String ( 'string'); then it is the object type.

There is no basic types of properties and methods, but you can still use the method attribute of the object only. This is because when using the method attribute of the basic types, implicit background will create the basic types of objects, and then after the destruction of the object

== operator

== For instance, if the parties are not the same type of comparison, it would typecast

Judging process:

  1. Both will first determine whether the same type. The word is the same than the size of the
  2. Types are not the same, then it will be cast
  3. Returns will first determine whether the comparison null and undefined, yes true
  4. Analyzing both the number and the type is a string, the string will then be converted to a number
1 == '1'
      ↓
1 ==  1
  1. Determine whether one of the parties is boolean, then it will be put into boolean number and then judge
'1' == true
        ↓
'1' ==  1
        ↓
 1  ==  1
  1. Wherein determining whether the object and the other one is a string, number, or symbol, then it will be the object into primitives and then judge
'1' == { a: 'b' }
        ↓
'1' == '[object Object]'
  1. On both sides of the object, then different references if not the same object, are false

Note that, as long as NaN occur, it must be false, because even their own are not equal to NaN NaN
to NaN, is to use the method to determine the global functionisNaN()

=== operator

Type does not turn, directly determine the type and value are the same.
But NaN === NaN or false

{} Is equal to true or false

var a = {};

a == true // -> ?
a == false // -> ?

The answer is that both are false
because a.toString () -> '[object Object]' -> NaN

1 Number (1) What is the difference

var a = Number(1) // 1
var b = new Number(1)  // Number {[[PrimitiveValue]]: 1}
typeof (a) // number
typeof (b) // object
a == b // true
  • var a = 1 is a constant, and Number (1) is a function
  • new Number (1) returns an object
  • a == b is true because it is in the evaluation process will always be forced into the original data type instead of objects, for example the following code:
typeof 123 // "number"
typeof new Number(123) // "object"
123 instanceof Number // false
(new Number(123)) instanceof Number // true
123 === new Number(123) // false

console.log (!! (new Boolean (false)) What is the output [confusing]

true
object instance of Boolean Boolean wrapper object, the object only when null and undefined, will be identified as the false value of the Boolean, Boolean wrapper object itself is an object, the object -> Boolean is true, so the new Boolean (false) actually Boolean true, look at the following code:

if(new Boolean(false)){
    alert('true!!');
}

ValueOf is used only after the actual transformation Boolean value, same as above with the wrapper object original data conversion explained:

!!(new Boolean(false))  //true
(new Boolean(false)).valueOf() //false

How to determine a data is not Array

  • Array.isArray(obj)
    • ECMAScript 5 kinds function, when using ie8 will be a problem.
  • obj instanceof Array
    • When configured in an array for detecting a different window or the iframe will fail. This is because each iframe has its own execution environment, the prototype chain does not share with each other, so in this case to determine whether an object is an array will fail. At this point we have a better way to determine whether an object is an array.
  • Object.prototype.toString.call(obj) == '[object Array]'
    • This method is more reliable
  • obj.constructor === Array
    • constructor function returns the property to create a reference to this object

Object.prototype.toString

If the original type, he copies the original packaging type is a reference type, then call the corresponding method

function dd(){}
var toString = Object.prototype.toString;
toString.call(dd);          //[object Function]
toString.call(new Object);  //[object Object]
toString.call(new Array);   //[object Array]
toString.call(new Date);    //[object Date]
toString.call(new String);  //[object String]
toString.call(Math);        //[object Math]
toString.call(undefined);   //[object Undefined]
toString.call(null);        //[object Null]
toString.call(123)          //[object Number]
toString.call('abc')        //[object String]

obj.toString() 和Object.prototype.toString.call(obj)

The same is to detect the object obj call toString methods, results obj.toString () results and Object.prototype.toString.call (obj) is not the same, why is this?

This is because the Object toString prototype method, the Array, function, etc. As an example of Object type are rewritten toString method. When calling toString method different object types, according to the knowledge of the prototype chain, toString method is invoked (function type string function returns the contents of a corresponding body after rewriting, Array type elements returned string .... .), and not to call the prototype method toString (specific type of the returned object) on the object, so using obj.toString () object type can not be obtained, it can be converted to a string type obj; therefore, to obtain the desired the specific type of the object, the prototype object toString method should be called on.

The following code output operation results

1 + "1"

2 * "2"

[1, 2] + [2, 1]

"a" + + "b"
  • 1 + "1"
    • Additive operators: If only one of the operands is a string, then the other operand is converted to a string, and then stitching together two strings
    • So the value: "11"
  • 2 * "2"
    • Multiplicative operator: if the operand is not a value in the background is called Number () converts it to the value
  • [1, 2] + [2, 1]
    • Javascript all objects are basically first call valueOf method, if not the number, then call toString method.
    • Therefore toString method adding two array object, is: "1,22,1"
  • "a" + + "b"
    • Behind the "+" as a unary operator, if the operand is a string, the method calls Number value operand converted, if the operand value can not be converted, compared NaN.
    • So is: "aNaN"

Guess you like

Origin www.cnblogs.com/nayek/p/11729909.html