Type conversion in js

Keywords: Javascript ECMAScript

Type conversion is divided into two types: forced type conversion and implicit type conversion

Cast type

Forced type conversion mainly refers to three functions: Number(), String(), and Boolean. Manually convert various types of values into numbers, strings, or boolean values

Number()

There are two main types: one is that the parameter is the original type, and the other is that the parameter is the object

Value of original value type

//Value, after conversion, it is still the original value
Number(324) //324
//String: if a bit value can be parsed, it is converted to the corresponding value
Number('324') // 324
//String: if it cannot be parsed into a numeric value, NaN is returned
Number('324abc')// NaN
//Convert empty string to 0
Number('')//0

//Boolean: true is 1, false is 0
Number(true)//1
Number(false)//0

//undefined to NaN
Number(undefined) // NaN

//null to 0

Number(null) //0

The Number function converts a string to a numeric value, which is much stricter than the parseInt function. Basically, as long as one string cannot be converted to a numeric value, the whole string will be converted to NaN

parseInt('42 cat')// 42

Number('42 cat') // NaN

In addition. Both parseInt and Number functions automatically filter the leading and suffix spaces of a string

parseInt('\t\v\r12.34\n') // 12
Number('\t\v\r12.34\n') // 12.34

object

The simple rule is that when the parameter of the Number method is an object, NaN will be returned, unless it is an array containing a single value

Number ({a:1}) // NaN
Number ([1,2,3]) // NaN
Number ([5]) // 5
Number (['1']) // 1
Number ([]) // 0

reason  

  • Call the valueOf method of the object itself. If the value of the original type is returned, the Number function will be used directly on the object instead of subsequent steps
  • 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 object uses the Number function instead of subsequent steps
  • If the toString method returns an object, an error is reported
var obj = {a:1}
Number(obj) // NaN

Equivalent to

if (typeof obj.valueOf() === 'object') {
Number(obj.toString());
} else {
Number(obj.valueOf());
}

String()

The String function can convert any type of value into a String. The conversion rules are as follows:

Original type:

  • Numeric value: converted to the corresponding string
  • String: fixed
  • Boolean: true to "true" and "false to" false“
  • Undefined: convert to 'undefined'
  • Null: convert to 'null'
String(123) // "123"
String('abc') // "abc"
String(1e21) // '1e+21' 
String(true) // "true"
String(undefined) // "undefined"
String(null) // "null"

object

If the parameter of the string method is an object, it returns a type string. If it is an array, it returns the string form of the array, which is equivalent to calling the Array.prototype.join() method of the array

String({a: 1}) // [object, object]

Strng ([]) // ''
string([1,2,4]) // "1,2,4"

//null or undefined in the array will be treated as an empty string
String([1,undefined,3]) // "1,,3"

Conversion rules of String and Number method   Basically the same, except that the toString method is called first and the valueOf method is called later

Similarly, toString and valueOf can be customized

String ({
toString: function () {
return 3;
}
})
// "3"
String ({
valueOf; function () {
return 2;
}
})
// "[object, object]"

String ({
valueOf: function () {
return 2;
},
toString: function () {
return 3;
}
})
// "3"

Boolean()

The Boolean() function can convert any type of value to a Boolean value

His conversion rule is relatively simple. Except that the conversion result of the following five values is false, all other values are true

  • undefined
  • null
  • 0 (including - 0 and + 0)
  • NaN
  • '' (empty string)

The conversion result of all objects (including empty objects) is true. Even the Boolean object new Boolean(false) corresponding to false is true

Implicit conversion

Implicit conversion is based on cast

In the following three cases, javascript will automatically convert the data type,

  • First, different types of data operate on each other
// One of the most common is the operation of numbers and strings
//+The operator converts a number to a string, while - / * converts a string to a number

123 + '123' // 123123
123-'123' // 0
'123'/123 // 1
  • Boolean evaluation of data of non boolean type
if('abc') {
console.log('hello')
}Except for the following values true
undefined null +0 -0 NaN ''(Empty string)
You can use the! Operation to convert it to true 
if (! undefined && !null && !0 && !NaN && ! ''){
console.log('hello')
}


//In the following way, sometimes an expression is converted to a Boolean value

expression ? true : false
  • Use unary operators for non numeric types
+ {foo : 'bar'} // NaN
- [1,2,3] // NaN
//In the unary operator, + is to add to the string and convert it into 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"


'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

js = = and===

The rules are as follows:

Equal and unequal --- convert first in comparison (= =)

Congruent and incomplete --- only compare without conversion (= = =)

==Is to compare values and = = = not only compare values but also compare types

==Comparison process of

  • If an operand is Boolean, convert it to a numeric value before comparing equality --- false to 0 and true to 1
  • If one operand is a string and the other is a numeric value, you want to convert the string to a numeric value before comparing equality
  • If one operand is an object and the other operand is not, the valueOf() method of the object is called to compare the obtained basic types according to the previous rules
  • If the types of two values are the same, compare whether = = = is the same
  • If the two value types are different, it is also possible to compare them, and the type will be implicitly converted
  1. If one is null and the other is undefined, then it is equal
  2. If one is a string and the other is a numeric value, convert the string to a numeric value and compare it

===Comparison process of

  • If the types are different, they must not be equal
  1. If both are numeric values and are the same value, they are equal. If they are NaN, they are not equal
  2. If two are strings and each position is the same, they are equal, otherwise they are not equal
  3. If both values are true or false, they are equal
  4. If both values are null or undefined, they are equal
1 == 1 // true
1 === Number(1) // false
NaN == NaN // false

null == undefined // true
1 == '1' //true
1 === '1' // false
'9'< '10' // false: the standard glue of string is compared by bit. The ASIC code of numeric character comparison is 0-9 48 - 57
 The order of uppercase characters is 65-90 The order of lowercase characters is 97-122

typeof [] === 'array' // false typeof can only judge the basic type, and the object can only judge that the result of object typeof [] is object

'null' == 'undefined' // false this is a comparison of strings
[] == ![] // true
{} == !{} // false

According to the operator priority, the priority of! Is greater than = =, so it will be executed first! []

! operator will convert to boolean type, where null, undefined, NaN, ('') is false, and the rest are true

So the result of! [] is false  

According to the above rules (if an operand is Boolean, it will be converted to a value before comparing equality) then! [] = false = 0

Then the comparison becomes [] = = 0

Then according to the above rules (if one operand is an object and the other operand is not, call the valueOf() method of the object to obtain its value, compare the obtained basic type according to the previous rules, and call the toString() method if the object has no valueOf() method)

For empty arrays, []. Tostring() - [1jeemaa1] ''   (empty string returned)

The comparison becomes' '  == 0

Then according to the above rules (if one operand is a string and the other operand is a value, convert the string to a value before comparing equality)

Number ('') -> 0

It becomes 0 = = 0    // true

The summary is as follows:

[] == ![] -> [] == false  -> [] == 0  -> '' == 0 -> 0 == 0 -> true

The same is true for {} = =! {}

The key is {}. Tostring() - > Nan

{} ==!{} -> {} == false -> {} == 0 -> NaN == 0 -> false

Posted by richardwarren on Sat, 30 Oct 2021 23:34:40 -0700