JS type judgment and conversion

I. Introduction

The data types in js are divided into 基本数据类型and 引用数据类型, 基本数据类型including: String, Number, Null, Undefined, Boolean, Symbol (new), BigInt (new); 引用数据类型there are: Object, and Object also contains Array and Function. As we all know, js is a weakly typed language. It is not necessary to specify the variable type when defining a variable, and the type is only known when the variable is used; and when the types of variables are different but need to be calculated or compared, implicit type conversion will occur. It is easy to cause code errors. 强制类型转换Let's take a look at the sum in js 隐式类型转换;

2. The way of judging the type

2.1 typeof

All basic data types can be used typeofto judge. What should be noted in the reference type is that there is typeofno null, and the return value of Array and Object is 'object'; this is because the value in JavaScript is represented by a label representing the type and the actual data value. of. The type tag of the object is 0. Since nullrepresents a null pointer (0x00 on most platforms), the type label of null is 0, typeof nullso it is returned "object". This is a bug that was created in the language and has never been fixed.

typeof 2 			// 'number'
typeof null 		// 'object'
typeof Symbol(2) 	// 'symbol'
typeof 3n			// 'bigInt'
typeof []			// 'object'
typeof {
    
    }			// 'object'
typeof function(){
    
    }	// 'function'

Summarize:

  • typeof can judge all primitive data types except null
  • typeof null === 'object' is a legacy issue and cannot be changed.
  • typeof cannot judge Array and Object types

2.2 instanceof

The instanceof operator is used to detect whether prototypethe attribute appears on the prototype chain of an instance object. This involves the knowledge of constructors, prototypes and prototype chains. Take an example to understand:

// 常量arr是调用Array的构造函数返回的实例
const arr = [1,2,3,4]// arr实例可以调用Array数组中的属性和方法,arr的原型链指向Array原型中
arr.__proto__ === Array.prototype //  true
// 所以就可以使用instanceof判断是否是数组
arr instanceof Array;   // true
// 注意:上面讲到typeof无法区分Array和Object,这是因为Array的原型链指向Object的原型上,而原型链的终点是null,所以就会出现下面情况
arr instanceof Object;   // true
// arr完整的原型链
arr.__proto__.__proto__.__proto__ === null;

The above example is just a brief description of the search principle of instanceof. The prototype and prototype chain are not explained in depth. Next time, we will sort it out and talk about it separately;

Summarize:

  • instanceof is not suitable for judging basic types, it can only be used to judge reference types;
  • It is also impossible to accurately judge the Object. If it is judged whether the variable is an Object, arr will also return true;

2.3 constructor

The constructor property returns Object's constructor (used to create instance objects). It can be understood as who is the constructor of this variable. can have a property for any type except nulland (undefined since there are no corresponding constructors for those two) ;constructor

// 原始类型
console.log((1n).constructor === BigInt); // true
console.log(('str').constructor === String); // true
console.log(Symbol(3).constructor === Symbol); // true
// 引用类型
console.log(([]).constructor === Array); // true
console.log(({
    
    }).constructor === Object); // true
// 内置函数对象的构造函数为 Function
console.log(Array.constructor === Function); // true
console.log(String.constructor === Function); // true

Summarize:

  • The constructor can accurately determine the data type, but cannot determine null and undefined
  • Modifying the prototype of the instance before creating the instance will make the constructor unreliable
  • The constructor of the built-in function object is Function

2.4 Object.prototype.toString.call()

Every object has a toString()method that is called automatically when the object is represented as a literal value, or when an object is referenced in the expected string manner. By default, toString()methods are inherited by every Objectobject . If this method is not overridden in a custom object, toString()returns "[object type ]", where typeis the type of the object.

Object.prototype.toString.call(null).slice(8,-1);  // Null
Object.prototype.toString.call([]).slice(8,-1);    // Array
Object.prototype.toString.call({
    
    }).slice(8,-1);    // Object

Summarize:

  • This is the most accurate way to determine the type
  • It is recommended to use this to judge any type

3. Mandatory type conversion

The mandatory type conversion is mainly introduced here 其他类型转换为基本数据类型, while the basic data type conversion reference type needs to see whether there is a corresponding method on the corresponding basic data type prototype.

3.1 Convert to String

There are two ways to convert other types to string type, String(val)and val.toString(). It should be noted that the sum val.toString()cannot be nullconverted undefined. Because the toString() method calls the built-in toString method on the prototype object of the target value, and null undefined` has no corresponding prototype object, the toString() method cannot be called.

null.toString();	// TypeError: Cannot read properties of null (reading 'toString')
undefined.toString();// TypeError: Cannot read properties of null (reading 'toString')
String(null);		// 'null'
String(undefined);	// 'undefined'
String(1);			// '1'
String({
    
    });			// '[object Object]'
String([]);			// ''

3.2 Convert to Number

Convert other types to number and Numbercall . One thing to note is that the object is converted to a string NaN; if the string contains a value that is not a number, the conversion will also become NaN.

Number(null); 		// 0
Number(undefined);	// NaN
Number(true);		// 1
Number(false);		// 0
Number([]);			// 0
Number({
    
    });			// NaN
Number('12');		// 12
Number('12a');		// NaN

3.3 Conversion to Boolean

Casting to Boolean is simple, just call the method Boolean(). Only the converted value of the six cases is false, and the others are true. Convert to false:0、false、NaN、' '、null、undefined

3.4 null and undefined

Null and undefined are relatively special values ​​in JS, undefinedwhich represent the original value of 'no'; null represents an object that does not yet exist, and they do not have their own prototype object; so there is no other type of conversion to these two types.

3.5 Reference data types

When the reference type is converted, a method toPrimitive() inside js will be called. This method receives two parameters, one parameter is the object to be converted, and the other method receives an expected type, string or number.

  • When the expected value is number, the valueOf method will be called. If the returned value is not the original value, the toString method will continue to be called.
  • When the expected value is string, the toString method will be called. If the returned value is not the original value, the valueOf method will continue to be called.

4. Implicit type conversion

Scenarios that trigger implicit type conversions:

  • during arithmetic operations
  • When comparing logic

4.1 When doing arithmetic operations

4.1.1 +Addition operator:
  • When the types to be added are all numeric types, the addition is performed normally.
  • When there are other types of elements, they will be converted to strings first, and then the strings will be added and spliced.
  • When performing string concatenation, the reference data type will call its own toString method. If the return value is not the original value, it will continue to call its own valueOf method. For non-reference data types: if v.isString() is true, it will call v.toString() . Otherwise, it converts the value to a string.
4.1.2 -、/和*Operators:
  • Non-numeric types will be converted to numeric types
  • If it is a primitive data type, the Number() method will be called for conversion
  • If it is a reference data type, it will call its own valueOf method for conversion. If it is not the original value after conversion, it will call the toString method for conversion. If it is not a number after conversion, it will call Number() for conversion. If it is not a number after conversion, it will returns NaN.

4.2 Logic comparison

4.2.1 ==Equality and !=inequality comparisons
  1. If both operands are objects, returns only if both operands refer to the same object true.
  2. Returns if one operand is nulland the other is .undefinedtrue
  3. If the two operands are of different types, an attempt is made to convert them to the same type before comparison:
    1. When a number is compared to a string, an attempt is made to convert the string to a numeric value.
    2. BooleanConverts the Boolean operand to 1 or 0 if one of the operands is .
      • If yes true, convert to 1.
      • If yes false, convert to 0.
    3. If one of the operands is an object and the other is a number or string, an attempt is made to convert the object to a primitive value using the object's valueOf()and method.toString()
  4. If the operands have the same type, they are compared as follows:
    • String: trueReturned only if both operands have the same characters in the same order.
    • Number: trueReturned only if both operands have the same value. +0and are -0treated as the same value. NaNReturns if either operand is false.
    • Boolean: returns trueonly if the operand is two trueor two .falsetrue
4.2.2 !Conversion

!The following data will be converted into a Boolean value first, and then negated.

4.2.3 <、<=、>、>=Comparison conversion
  • If both operands are numbers, compare the size directly
  • If both operands are strings, compare the ascii code bit by bit
  • If it is a number of other basic data types, or a string;
  • If it is a reference data type, it will be converted to a string.

5. Comprehensive example exercises

console.log(123 + +'123' == '123123');
console.log({
    
    } == []);
console.log({
    
    } == true);
console.log('777' < '8');
// 思考题
100 + true + 222 + null + undefined + "123" + [] + null + false = ???
  1. false, +'123'an implicit conversion to number 123 occurs, and finally is 246 == '123123'; so false
  2. False, both are converted to reference types '[object Object]' == ''; so it is false
  3. false, see the above 4.2.1 rule, true is converted to 1, and finally is '[object Object]' == 1; so false.
  4. true, please refer to the 4.2.3 rule, when both operands are strings, the comparison is an ASCI value
  5. Topic 5: Results'NaN123nullfalse'

Summarize:

  • To avoid calculations of different data types when performing arithmetic operations, you can manually convert to the same type and then perform calculations; avoid syntax errors caused by NaN in the calculated value;
  • Comparisons take into account implicit type conversions between two values;
  • When judging if, not only implicit conversion but also the precedence between operators should be considered (this has been summarized before);
  • JS is very tolerant to grammar, but you must strictly demand yourself when writing code:
    • There must be spaces between arithmetic operators and variables to avoid implicit conversion;
    • end after the previous sentence ;ends;
    • Variable naming should be familiar with the name;
    • Perform operation comparison after conversion to the same type;

Guess you like

Origin blog.csdn.net/IO14122/article/details/127125832