js forced type conversion

Forced type conversion

Coercive type conversion: refers to the conversion of a data type into other data types.
Type conversion mainly refers to: conversion of other data types into String, Number, Boolean

1. Convert other data types to String
method 1. Call the toString() method of the converted data type
Syntax: a.toString();

This method will not affect the original variable, it will return the result of the conversion.
Var a=a.toString();

But note that there is no toString() method for null and undefined, and
an error will be reported if their method is called

Method 2: Use the String() function and pass the converted data to the function as a parameter. Syntax: var a=String(a);
When using the String() function to do coercive type conversion,
for Number and Boolean, it’s actually calling toString () method
But for null and undefined, the toString() method
will not be called. It will directly convert the null to "null" and convert the literal to a string.
Undefined converts to the "undefined" literal to convert to a string

2. Convert other data types to Number

Method 1: Use the Number() function
to
convert a string to a number: 1. If it is a pure number string, it is directly converted to a number
2. If there is a non-digital content in the
string , it is converted to NaN 3. If the string is Empty string and many spaces are converted to 0

Boolean to number: true to 1 false to 0
null to number: null to 0
Undefined to number: undefined to NaN

3. Convert other data types to Boolean

Use Boolean() function
Number→Boolean Except for 0 and NaN, the rest are true
string→Boolean Except for the empty string, the rest are true
null→Boolean false
undefined→Boolean false

Guess you like

Origin blog.csdn.net/weixin_48769418/article/details/107522599