First, data types

  • Seven primitive types:

    • Undefined
    • Null
    • Boolean
    • Number
    • BigInt
    • String
    • Symbol
  • One complex data type: Object

For detailed descriptions of the various data types, see togoblog.cn/javascript-…

Second, type judgment

1, the typeof

Typeof is a unary operator that precedes its single operand, which can be of any type. The return value is a string representing the operand type.

let a;
const s = Symbol('foo');

console.log(typeof a); // undefined
console.log(typeof null); // object
console.log(typeof 'String'); // string
console.log(typeof 1); // number
console.log(typeof BigInt('9007199254740993')); // bigint
console.log(typeof false); // boolean
console.log(typeof s); // symbol
console.log(typeof {}); // object
Copy the code

Note that these are all lowercase strings.

Typeof can also detect function types:

function func() {}console.log(typeof func); // function
Copy the code

So typeOF can detect a total of eight types of values.

Typeof (Array, Function, Date, RegExp, Error, etc.) returns all types of Object:

const date = new Date(a);const error = new Error(a);console.log(typeof date); // object
console.log(typeof error); // object
Copy the code

So how do you detect that?

2, the Object. The prototype. ToString

Object. The prototype. ToString: es5. Making. IO / # x15.2.4.2

Let’s try this:

console.log(Object.prototype.toString.call(undefined)); // [object Undefined]
console.log(Object.prototype.toString.call(null)); // [object Null]

const date = new Date(a);console.log(Object.prototype.toString.call(date)); // [object Date]
Copy the code

This method returns a string consisting of object and class and], where class is the internal property of the object being judged. So, we can use the Object. The prototype. The toString method to identify more types.

let a;
const s = Symbol('foo');
const date = new Date(a);const array = [1.2.3];
const reg = /a/g;
const error = new Error(a);const func = function a() {};console.log(Object.prototype.toString.call(a)); // [object Undefined]
console.log(Object.prototype.toString.call(null)); // [object Null]
console.log(Object.prototype.toString.call('String')); // [object String]
console.log(Object.prototype.toString.call(1)); // [object Number]
console.log(Object.prototype.toString.call(BigInt('9007199254740993'))); // [object BigInt]
console.log(Object.prototype.toString.call(false)); // [object Boolean]
console.log(Object.prototype.toString.call(s)); // [object Symbol]
console.log(Object.prototype.toString.call({})); // [object Object]
console.log(Object.prototype.toString.call(date)); // [object Date]
console.log(Object.prototype.toString.call(array)); // [object Array]
console.log(Object.prototype.toString.call(reg)); // [object RegExp]
console.log(Object.prototype.toString.call(error)); // [object Error]
console.log(Object.prototype.toString.call(func)); // [object Function]
Copy the code

Even more can be detected:

console.log(Object.prototype.toString.call(Math)); // [object Math]
console.log(Object.prototype.toString.call(JSON)); // [object JSON]
function main() {
  console.log(Object.prototype.toString.call(arguments)); // [object Arguments]
}
main();
Copy the code

Since the resulting string is not that neat, we can encapsulate it:

const detectType = (obj) = > {
  const classType = {
    '[object Boolean]': 'boolean'.'[object Number]': 'number'.'[object String]': 'string'.'[object Function]': 'function'.'[object Array]': 'array'.'[object Date]': 'date'.'[object RegExp]': 'regexp'.'[object Object]': 'object'.'[object Error]': 'error'.'[object Null]': 'null'.'[object Undefined]': 'undefined'.'[object BigInt]': 'bigint'.'[object Symbol]': 'symbol'};return ((typeof obj === 'object' || typeof obj === 'function')? (classType[Object.prototype.toString.call(obj)] || 'object')
    : typeof obj);
};
Copy the code

Type conversion

1. Cast

A cast is used to manually convert a value of various types to a Number, String, or Boolean value using the Number, String, and Boolean functions.

1.1 the Number ()

Using the Number function, you can convert any type of value to a numeric value.

The following is divided into two cases, one is when the parameter is a primitive type of value, the other is when the parameter is an object.

(1) Primitive type value

// Value: the original value after conversion
Number(324); / / 324

// String: If it can be parsed to a numeric value, it is converted to the corresponding numeric value
Number('324'); / / 324

// String: If it cannot be parsed as a number, return NaN
Number('324abc'); // NaN

// The empty string is converted to 0
Number(' '); / / 0

// Boolean values: true to 1, false to 0
Number(true); / / 1
Number(false); / / 0

// undefined: becomes NaN
Number(undefined); // NaN

// null: converts to 0
Number(null); / / 0

// Symbol: cannot be converted, an error will be reported
Number(Symbol('foo')); // TypeError: Cannot convert a Symbol value to a number
Copy the code

The Number function converts a string to a Number more rigorously than the parseInt function — as long as one character cannot be converted to a Number, the entire string is converted to NaN.

parseInt('42 cats'); / / 42
Number('42 cats'); // NaN
Copy the code

The parseInt and Number functions also have something in common: they both automatically filter leading and trailing Spaces in a string.

parseInt('\ t \ n \ r12.34 \ n'); / / 12
Number('\ t \ n \ r12.34 \ n'); / / 12.34
Copy the code

(2) Objects

The rule is that the Number method returns NaN when its argument is an object, unless it is an array containing a single numeric value.

Number({ a: 1 }); // NaN
Number([1.2.3]); // NaN
Number([5]); / / 5
Copy the code

The rules for conversion run like this:

The first step is to call the valueOf method of the object itself. If a value of the original type is returned, the Number function is used directly on the value without further steps.

Second, if the valueOf method still returns an object, call the toString method of the object itself instead. If the toString method returns a value of the original type, the Number function is used on the value without further steps.

Third, if the toString method returns an object, an error is reported.

1.2 the String ()

The String function converts a value of any type to a String as follows:

(1) Primitive type value

  • Value: Converts to the corresponding string.
  • String: the original value after conversion.
  • Boolean value:trueConvert to string"true".falseConvert to string"false".
  • undefined: Converts to a string"undefined".
  • null: Converts to a string"null".

(2) Objects

If it is an object, return a type string; If it is an array, return the array as a string.

String({ a: 1 }); // "[object Object]"
String([1.2.3]); / / "1, 2, 3"
Copy the code

The conversion rules behind the String method are basically the same as for the Number method, except that the order in which valueOf and toString are executed is reversed:

  1. Call the object’s own firsttoStringMethods. If a value of the original type is returned, the value is usedStringFunction, do not perform the following steps.
  2. iftoStringMethod returns an object and calls the original object’svalueOfMethods. ifvalueOfMethod returns a value of the original typeStringFunction, do not perform the following steps.
  3. ifvalueOfMethod returns an object, an error is reported.
1.3 Boolean ()

Boolean functions can convert a value of any type to a Boolean value. All values are true except for the following six values that convert to false.

  • undefined
  • null
  • 0+ 0
  • NaN
  • ' '(Empty string)
  • false

Note that all objects (including empty objects) convert to true, even the corresponding Boolean new Boolean(false) is true:

Boolean({}); // true
Boolean([]); // true
console.log(Boolean(new Boolean(false))); // true
Copy the code

2, automatic conversion

There are three situations where automatic type conversions can occur:

  • Different types of data operate on each other

  • Evaluate booleans for data that is not a Boolean value type

  • Use unary operators (that is, + and -) for values of non-numeric types

The rule for automatic conversion is to call the conversion function of the expected type of value. For example, if a location is expected to be a stringStringFunction to convert. If the position can be either a string or a value, it defaults to a value.

Because automatic conversions are uncertain and difficult to debug, it is recommended to use the Boolean, Number, and String functions for all explicit conversions where booleans, numeric values, and strings are expected.

2.1 Automatic conversion to A Boolean value

JavaScript automatically converts non-Booleans to Booleans where it expects a Boolean value (such as the conditional part of an if statement). The system automatically calls Boolean functions internally.

Therefore, all but the following six values are automatically converted to true.

  • undefined
  • null
  • + 00
  • NaN
  • ' '(Empty string)
  • false

In the following example, each value in the condition section is equivalent to false, which becomes true when the negation operator is used.

if (!undefined&&!null&&!0&&!NaN&&!' '
) {
  console.log('true');
} // true
Copy the code

The following two ways are sometimes used to convert an expression to a Boolean value. They also call Boolean functions internally.

/ / write one
expression ? true : false

/ / write two!!!!! expressionCopy the code
2.2 Automatic conversion to a String

JavaScript automatically converts a non-string value to a string where it expects a string. The rule is to convert a value of the compound type to a value of the primitive type, and then convert the primitive type to a string.

Automatic conversion of strings occurs mainly during string addition operations. When one value is a string and the other is a non-string, the latter is converted to a string.

'5' + 1 / / '51'
'5' + true // "5true"
'5' + false // "5false"
'5' + {} // "5[object Object]"
'5' + [] / / "5"
'5' + function (){} // "5function (){}"
'5' + undefined // "5undefined"
'5' + null // "5null"
Copy the code

This automatic conversion is prone to error.

const obj = {
  width: '100'
};

obj.width + 20 / / "10020"
Copy the code

In the code above, the developer might expect to return 120, but because of the automatic conversion, a character 10020 is actually returned.

2.3 Automatic conversion to values

JavaScript automatically converts the parameter value to a value where it is expected to be. The Number function is automatically called internally.

Except for the addition operator (+), which may convert an operator to a string, all operators automatically convert an operator to a number.

'5' - '2' / / 3
'5' * '2' / / 10
true - 1  / / 0
false - 1 // -1
'1' - 1   / / 0
'5' * []    / / 0
false / '5' / / 0
'abc' - 1   // NaN
null + 1 / / 1
undefined + 1 // NaN
Copy the code

In the code above, the operators on both sides of the operator are converted to numbers.

Note: null is 0 when converted to a value, and undefined is NaN when converted to a value.

Unary operators also convert operators to numbers.

+'abc' // NaN
-'abc' // NaN
+true / / 1
-false / / 0
Copy the code