JavaScript data type, data conversion, detection method

JavaScript data type, data conversion, detection method

Guide

Today we come to understand the data types in js, the display conversion and implicit conversion between data, and some methods of how to detect these data types. There are 7 data types in js, which are as follows:

  • undefined type
  • null type
  • string string type
  • number type
  • boolean Boolean value type
  • Symbol type
  • object type

type of data

undefined type

undefined is a special value in js, and it is also a false value. For a variable that has been declared but not initialized, js will automatically assign the value undefined to the variable.

let name; console.log(name)//undefined Copy code

There is a method typeof to detect the data type, but this method has a problem, please see below:

let name; console.log(typeof name)//undefined console.log(typeof age)//undefined Copy code

There is no declaration of age, but the return value is undefined, so we have to initialize our variables, so that when using typeof to detect variables, returning undefined means that the variable is not declared, rather than declared without initialization

null type

Null is also a special value in js, null represents a pointer to an empty object, so typeof is used to detect the reason for returning object. Null is also a false value. Undefined is derived from null. All surfaces are equal to null == undefined, but the usage of null is different from undefined. If we want to assign a value to a variable, we usually initialize one first. null value to indicate that this variable will store the object

boolean type

Boolean is a Boolean value. There are two values true and false, which are case sensitive. All True and Flase are not Boolean values. You can also explicitly convert the data to boolean, you can call the Boolean() function, the rules for converting boolean to different data types are listed below

type of dataConvert trueConvert false
Booleantruefalse
StringNon-empty string"" (empty string)
NumberNon-zero values (including infinite values)NaN, 0
ObjectAny objectnull
Undefineddoes not existundefined

Boolean() is an explicit conversion, as well as an implicit conversion, please see below:

let message; if(message) {} //Write like this in the if statement, the message will be implicitly converted to Boolean type to judge Copy code

Number type

The number type uses the IEEE 754 format to represent integers and floating-point numbers. The length is 64 bits and the memory occupies 8 Bytes.

1. Integers can be represented by decimal, octal and hexadecimal

let a = 10//decimal 10 let b = 070//octal 56 let c = 0xA//hexadecimal system 10 Copy code

2. Floating point numbers

let a = 1.1 let b = 0.1 let c = .1//not recommended //can also be expressed in scientific notation let floatNum = 3.125e7;//equal to 31250000 Copy code

3. The calculation of floating-point numbers may bring loss of precision

For example: 0.1 + 0.2 is equal to 0.300 000 000 000 000 04 But 0.5 + 0.5 will not have such a thing Copy code

4. Range of values

//maximum Number.MAX_VALUE 1.7976931348623157e+308 //minimum Number.MIN_VALUE 5e-324 //Exceeding the range will be converted to infinity, which can be signed Copy code

5. NaN

NaN is a special value, which means it is not a number

console.log(0/0);//NaN console.log(-0/+0);//NaN console.log(-0/NaN);//NaN Copy code

js mentioned an isNaN() function, isNaN() will try to convert the passed parameter into a value, if it can be converted into a value, it will return false, if it can t, it will return true

console.log(isNaN(NaN));//true console.log(isNaN(10));//false, 10 is a number console.log(isNaN("10"));//false, can be converted to a value of 10 console.log(isNaN("blue"));//true, cannot be converted to a number console.log(isNaN(true));//false, can be converted to a value 1 Copy code

6. Numerical conversion rules

js provides a function Number() that explicitly converts values. The conversion rules are as follows:

  • Value, return directly
  • Boolean, true returns
  • null, return 0
  • undefined, return NaN
  • String
    • The string contains only numeric characters, including the plus and minus signs (plus and minus signs) in front of the numeric characters, it will be returned as a converted decimal value, and the leading 0 of the numeric symbol will be ignored
    Number('123')//123 Number('-123')//123 Number('-00001')//-1 Copy code
    • The string contains only valid floating-point numeric characters. The value of the floating-point number is returned, and the leading 0 is also ignored. If the value after the decimal point is all 0, it will also be ignored
    Number('1.1')//1.1 Number('123.0000')//123 Number('123.001')//123.001 Copy code
    • The string contains only valid hexadecimal strings, it will be converted to the decimal value corresponding to the hexadecimal
    Number ( '0xA')//10 duplicated code
    • If the string is just an empty string, 0 is returned
    • If the string contains strings other than the above strings, NaN will all be returned
  • Object, first call the valueOf() method, and then perform the conversion according to the above method, if the conversion result is NaN, then call toString(), and then perform the conversion according to the above method
//1. Object {} Number({})//NaN var a = {} a.valueOf()//{} or the object itself a.toString()//"[object Object]" //So return NaN //2. Array[] Number([])//0 var a = [] a.valueOf()//[] itself a.toString()//"" (empty string) //so it returns 0 Copy code

7. parseInt()

parseInt(string, radix) parses a string and returns a decimal integer with the specified base. radix is an integer between 2-36 and represents the base of the parsed string.

Usually used to convert a string into an integer, this function accepts two parameters, one is the number to be converted, and the other is the base number to be converted into. The rules are as follows:

  • If the first character is not a numeric value or +,-signs, NaN is directly returned
  • If the first character is a numeric value or +,-signs, continue to search for the next character until the end of the string or a non-numeric character is encountered
  • The second parameter is converted into the corresponding hexadecimal number, effective is 2~36 digits, the default decimal number
  • If the first character is a numeric character, parseInt() will also recognize it automatically
parseInt('123bbb')//123 parseInt('12.1') //12 because the decimal point is not a valid numeric character let num1 = parseInt("10", 2);//2, parse according to binary let num2 = parseInt("10", 8);//8, parse in octal let num3 = parseInt("10", 10);//10, parsed in decimal let num4 = parseInt("10", 16);//16, parsed in hexadecimal let num3 = parseInt("0xA");//10, interpreted as a hexadecimal integer let num4 = parseInt(22.5);//22 let num5 = parseInt("70");//70, interpreted as a decimal value let num6 = parseInt("0xf");//15, interpreted as a hexadecimal integer Copy code

8. parseFloat()

The functions of parseFloat and parseInt are similar, the difference is that (1) the decimal point that appears for the first time is valid, the decimal point that appears for the second time is invalid, and (2) the leading 0 is ignored

let num1 = parseFloat("1234blue");//1234, parsed by integer let num2 = parseFloat("0xA");//0 let num3 = parseFloat("22.5");//22.5 let num4 = parseFloat("22.34.5");//22.34 let num5 = parseFloat("0908.5");//908.5 let num6 = parseFloat("3.125e7");//31250000 Copy code

String type

In general, there are three ways to define a variable as a string

let name = "abc"//double quotes let name1 ='abc'//single quote let name2 = `abc`//template literal Copy code

1. Character literal

Character literalmeaning
\nWrap
\ttabulation
\bbackspace
\rCarriage return
\fPage change
\Backslash (\)
'apostrophe
"Double quotes
`Backticks
\xnnThe character represented by hexadecimal code nn (where n is the hexadecimal digit 0~F), for example/x41 is equal to "A"
\unnnnThe Unicode character represented by the hexadecimal code nnnn (where n is the hexadecimal number 0~F), for example,/u03a3 is equal to the Greek character " "

2. Features

The string in js cannot be modified once it is created. If you want to modify the value of a string variable, you must destroy the original string and save the new string containing the new value to the variable.

3. Convert to string

  1. Use toString(), which is converted to a decimal string by default, and you can customize the effective base string
let num = 10; num.toString()//10 //Pass parameters num.toString(2)//'1010' num.toString(8)//'12' num.toString(16)//'a' Copy code
  1. Call the String() function, the rules are as follows
  • If there is a toString() method, call that method (without passing parameters)
  • If it is null, return "null"
  • If it is undefined, return "undefined"
  1. Use unary operator +
let str = 10 + '' + 123//"10123" copy the code

4. Template string

ES6 has a new syntax, which uses strings enclosed by backticks, and can use interpolation symbols for variable references. Any js expression can be used as an insert value

let name = `h` let name1 = `${name}i`//hi let name2 = `${name ==='h'?'x':'y'}i` //All inserted values will be converted into strings using the toString() method let obj = { toString(){ return 1 } } let name = `${obj}` console.log(name)//1 Copy code

Symbol type

Symbol is a symbol, a new data type in ES6. Symbols are primitive data types. Symbol instances are unique and cannot be changed. The purpose of symbols is to ensure the uniqueness of object attributes and avoid object attribute conflicts. Because it is primitive data, all typeof operations The result returned by the symbol is also "symbol"

let s = Symbol() console.log(typeof s)//"symbol" let obj = { [s]:'str' } console.log(obj[s])//'str' Copy code

Symbol has many uses, which will be explained separately later

Object type

Objects in js are a collection of data and functions, and you can add properties and methods to objects.

let obj = { name:'hi', getName: function(){ return this.name } } Copy code

Data conversion

Explicit conversion

String(), Number(), parseInt(), parseFloat(), Boolean()

String()

Conversion rules:

  • Basic data type
    • If there is a toString() method, call toString() to return the data
    • If it is null, return "null"
    • If it is undefined, return "undefined"
  • Reference type
    • First call the toString() method, if it returns a basic data type, use the above basic type rule conversion
    • If the returned data type is not a basic data type, call the valueOf() method. If the returned data type is a basic data type, use the above basic type rule conversion
    • If the return is not, an error is thrown

Number()

Conversion rules:

  • If the boolean values are true and false, true returns 1, false returns 0
  • If it is a number, return directly
  • If it is null, return 0
  • If it is undefined, NaN is returned
  • If it is a string
    • If the string contains numeric characters, including + and-symbols, it will be converted to decimal numbers
    • If the string contains a floating point number, it is converted to the corresponding floating point number
    • If the string contains a valid hexadecimal format such as "0xf", it will be converted to a decimal integer value corresponding to the hexadecimal value.
    • If the string is an empty string, 0 is returned
    • If the string contains characters other than the above, NaN is returned
  • If it is an object, first call the valueOf method and convert the returned value according to the above rules. If the conversion result is NaN, call the toString() method, and then convert according to the rules for converting strings.

Boolean()

Conversion rules:

  • If the boolean value is true, return true
  • If the boolean value is false, then return false
  • If it is a non-empty string, return true
  • If it is an empty string, it returns false
  • If it is a non-zero value, return true
  • If it is 0, NaN, then return false
  • If it is an object, return true
  • If it is null, return false
  • If it is undefined, return false

Implicit conversion (often called coercion)

1. Only judge variables

Implicit use of Boolean() conversion rules

var name ='' if(name) { //will not execute } var age = name? '1': '2' Copy code

2. Relational operators

Divided into two cases, one is the relational operator, and the other is the value equality operator

2.1 Relational operators (>, <, >=, <=)

The rules are as follows:

  • If both sides are numerical values, compare numerical values
  • If both are strings, compare the corresponding string codes one by one
  • If one is a numeric value, convert the other into a numeric value, and then compare
  • If one of them is an object, call the valueOf() method, and compare the results obtained according to the above rules. If there is no valueOf() method, call the toString() method, and the results obtained are compared according to the above rules.
  • If one is a boolean, convert it to a numeric value for comparison

2.2 Equality operator

The rules are as follows:

  • If one is a Boolean value, convert it to a numeric value for comparison, true is 1, false is 0
  • If one is a string and the other is a numeric value, try to convert the string into a numeric value and compare
  • If one is an object and the other is not, call the valueOf() method on the object to obtain the original value, and then compare according to the above rules. If the value obtained by valueOf is not a basic data type, call the toString() method to obtain the value, and then according to Comparison of the above rules
  • null and undefined values are equal, no data conversion is performed
  • If one is NaN, it will return false directly, if the other is also NaN, it will also return false directly. According to the rules, NaN and any data are not equal, including itself
  • If both are reference type objects, compare whether the two addresses point to the same object, if they are, return true, otherwise return false

Detection method

1. typeof

console.log(typeof "helloworld") ------------------>"string" console.log(typeof 123) ------------------>"number" console.log(typeof [1,2,3]) ------------------>"object" console.log(typeof new Function()) ------------------>"function" console.log(typeof new Date()) ------------------>"object" console.log(typeof new RegExp()) ------------------>"object" console.log(typeof Symbol()) ------------------>"symbol" console.log(typeof true) ------------------>"true" console.log(typeof null) ------------------>"object" console.log(typeof undefined) ------------------>"undefined" console.log(typeof'undefined') ------------------>"string" Copy code

2. instanceof

[1,2,3] instanceof Array -------->true new Date() instanceof Date -------->true new Function() instanceof Function -------->true new Function() instanceof function -------->false null instanceof Object -------->false Copy code

3. Judging method of object prototype chain: Object.prototype.toString.call()

console.log(Object.prototype.toString.call("123")) -------->[object String] console.log(Object.prototype.toString.call(123)) -------->[object Number] console.log(Object.prototype.toString.call(true)) -------->[object Boolean] console.log(Object.prototype.toString.call([1, 2, 3])) -------->[object Array] console.log(Object.prototype.toString.call(null)) -------->[object Null] console.log(Object.prototype.toString.call(undefined)) -------->[object Undefined] console.log(Object.prototype.toString.call({name:'Hello'})) -------->[object Object] console.log(Object.prototype.toString.call(function () {})) -------->[object Function] console.log(Object.prototype.toString.call(new Date())) -------->[object Date] console.log(Object.prototype.toString.call(/\d/)) -------->[object RegExp] console.log(Object.prototype.toString.call(Symbol())) -------->[object Symbol] Copy code