The data type

Data types in Javascript can be divided into simple data types and complex data types.

Simple data types: undefined, NULL, Boolean, number, string.

Complex data types: object Object includes arrays and functions.

Method for determining data types

Ex. : Var a = [34,4,3,54], b = 34, c = 'adsfas', d= ", e = true, f = null, g = function(){console.log(' I am a function ')}, h;Copy the code
  1. typeof

Typeof can accurately determine basic types (except null, typeof null=== “object”) :

  • string
  • number
  • boolean
  • undefined

Typeof returns the following two types for complex types:

  • Object Typeof returns object from an object, array, or null.
  • The function typeof operator does not return the function object.

// Typeof does not distinguish between objects, arrays, and null

typeof: Var a = [34,4,3,54], //object b = 34, //number c = 'adsfas', //string d= ", //string value is ", Type is "string" e = true, // Boolean f = null, //object g = function(){console.log(' I am function ')}, //function h; //undefinedCopy the code
  1. instanceof

When we need to know the exact type of an object, we can use the operator instanceof. Instanceof is used to determine whether A is an instanceof b. the expression A instanceof B returns true if A is an instanceof B, false otherwise. The important thing to note here is that Instanceof is testing prototypes

* Note: The instanceof operator can only be used on objects, not values of primitive type. The use of instanceof is limited, and it’s not easy to tell whether an instance is an array or an object or a method.

'hello' instanceof String          // false
null instanceof Object            // false
undefined instanceof Object      // false
Copy the code

Strings, null, and undefined are not objects, so return false.

  1. Object.prototype.toString.call()

ToString () is the prototype method of Object, which returns the concrete type of the current Object by default. This is an internal property of the format [object Xxx], where Xxx is the type of the object. Basically all object types can be obtained by this method.

  • What’s the difference between undefined and null?

Null and undefined are equal

console.log(null==undefined)   //true
console.log(null===undefined)  //false
Copy the code

Null: Type NULL, representing “null value”, representing an empty object pointer, using the Typeof operation to get “object”, so you can think of it as a special object value. Undefined: the undefined type. When a variable is declared uninitialized, undefined is obtained.