The data type in JS is the basis of learning JS, which is mainly divided into two categories:

  • The basic data types are number, String, Boolean, NULL, undefined, and Symbol and BigInt in the new ES6 syntax specification
  • Reference data types: object (plain object, array object, re object, Math, Date), function

Today we’ll take a quick look at the various data types:

Basic data types

According to the value of the operation

1, the number

  • Contains:
    • Positive, negative, 0

    • NaN

      Things to know about NaN:

      • Not a number Is not a significant number, but is of type number
      • NaN is not equal to any value (including itself)
      • NaN == NaN //=>false
    • Infinity: an infinite value, also of type number

  • Think: If you want to verify that n is a significant number, how do you verify it?
    • Since NaN is not a significant number, is it ok to simply use n==NaN?
    • A: No; NaN cannot be used to detect whether a number is a significant number because NaN itself is not a number and contains many things that are not a number, and NaN is not equal to itself.

From this we derive the concept of isNaN

1, the isNaN

  • Definition: profession used to verify that a value is not a significant number
  • The return value
    • Significant digit: Returns false
    • Non-significant digits: Returns true
console.log(isNaN(1)); //=>false
console.log(isNaN(NaN)); //=>true
console.log(isNaN(Infinity)); //=>false
console.log(isNaN('AA')); //=>true
console.log(isNaN('12.5')); //=>false
console.log(isNaN('12.5 px.)); //=>true
console.log(isNaN([])); //=>false
console.log(isNaN([10])); //=>false
console.log(isNaN([10.20])); //=>true
console.log(isNaN({})); //=>true
console.log(isNaN(null)); //=>false
console.log(isNaN(undefined)); //=>true
console.log(isNaN(Symbol(1))); / / = > an error
Copy the code
  • Note:
    • When testing with isNaN, if the value being tested is a non-numeric value, it needs to be converted to a numeric type before testing.

2. Convert other data types to numeric types

1) Number([value])

  • Definition: is a built-in JS conversion method that can “force” other data types to numeric types
  • 1. String to number
    • Only those that are both valid numeric characters can be converted to a specific number, and any non-valid numeric characters in the string result in NaN
    • Empty string to number ===>0
    console.log(Number('12')); / / = > 12
    console.log(Number('12.5')); / / = > 12.5
    console.log(Number('12px')); //=>NaN
    console.log(Number('12.5.0')); //=>NaN
    Copy the code
  • 2, Boolean to number
    • True converts to 1
    • False converts to 0
    console.log(Number(true)); / / = > 1
    console.log(Number(false)); / / = > 0
    Copy the code
  • 3. Turn the numbers around
    • Null is converted to 0
    • Undefined is converted to NaN
    console.log(Number(null)); / / = > 0
    console.log(Number(undefined)); //=>NaN
    Copy the code
  • 4, The Symbol is transferred to the number
    • The Symbol type cannot be converted to a number or an error will be reported
    console.log(Number(Symbol(13))); //=>Cannot convert a Symbol value to a number
    Copy the code
  • 5. Turn objects to numbers
    • Process:
      • 1. Convert obj to string “[object object]”
      • 2. Convert string to Number(“[object object]”)
    • Ordinary objects
    let obj={x:100};
    console.log(Number(obj)); //=>NaN
    Copy the code
    • Array object: An empty array is converted to a number 0
    /* * 1. First convert ARR to string: "10" * 2
    let arr = ["10"];
    console.log(Number(arr)); / / = > 10
    /* * 1. Convert ARR to a string: "10,20" * 2. Converting "10,20" to a number: NaN */
    arr = ["10"."20"];
    console.log(Number(arr)); //=>NaN
    console.log(Number([])); //=> []->'' Number('')->0
    console.log(Number(['AA'])); //=> ['AA']->'AA' Number('AA')->NaN
    Copy the code
    • The rest of the objects are basically nans
  • 6. Function to number
    • It’s all NaN
    console.log(Number(function func() {}));//=>NaN
    Copy the code

2) the parseInt ([value])

  • Definition: Searches from the leftmost part of the string, converts the found valid digit character to a digit, and ends the search until it encounters an invalid digit character
  • Principle:
    • The processing principle is different from Number
    • They convert strings to numbers (if the value is not a string, it needs to be converted to a string first and then converted to number).

3) parseFloat ([value])

  • With the parseInt difference
    • ParseFloat recognizes one more decimal point than parseInt
    console.log(Number('12px')); //=>NaN
    console.log(parseInt('12px')); / / = > 12
    console.log(parseInt('12px24')); / / = > 12
    console.log(parseInt('width:12px')); //=>NaN
    console.log(parseInt('12.5 px.)); / / = > 12
    console.log(parseFloat('12.5 px.)); //=>12.5 parseFloat recognizes one more decimal point than parseInt
    
    console.log(Number(true)); / / = > 1
    console.log(parseInt(true)); //=> First convert TRUE to string "TRUE" parseInt(' TRUE ') =>NaN
    console.log(parseInt(NaN)); //=>NaN
    console.log(Number(null)); / / = > 0
    console.log(parseInt(null)); //=> parseInt('null') =>NaN
    console.log(isNaN(Number(parseInt("0.8")))); / / = > parseInt (" 0.8 ") - > 0 Number (0) - > 0 isNaN (0) - > false
    
    console.log(Number(' ')); / / = > 0
    console.log(parseInt(' ')); //=>NaN
    Copy the code

3, methods,

In the category of Number, there are many common methods. This paper only lists two commonly used methods

1, toFixed ()

  • Syntax: numbers. ToFixed (N)
  • Definition: Reserve N decimal places (the final result is a string)
    let n = 3.1415926;
    console.log(n.toFixed(2)); / / = > "3.14"
    Copy the code

2, MAX_SAFE_INTEGER

  • Definition: maximum safe number (the largest integer that JS can recognize)
  • Number: 9007199254740991
  • Note: A new data type, BigInt, is provided in ES6 to manage numbers that exceed safe values
console.log(Number.MAX_SAFE_INTEGER); //=>9007199254740991 Maximum safe number (the maximum integer that JS can recognize effectively)
console.log(9007199254740992= =9007199254740993); //=>true should be different, but beyond the maximum value, JS cannot accurately calculateA new data type, BigInt, is provided in ES6: Manages numbers that exceed safe valuesconsole.log(BigInt(9007199254740992), BigInt(9007199254740993));
/* * Basic data type * number string Boolean NULL undefined symbol => BigInt New basic data type */
Copy the code

Mind mapping

2, the string

  • Definition: in JS, use single/double/back quotes to enclose strings

1, convert other data types to string types:

  • Methods:
    • String([value])
    • [value].toString()
  • Implicit conversion:
    • String concatenation
    • Before converting an object to a number, you need to convert it to a string
  • Common object to string: [object object]
  • Array objects converted to strings: “first item, second item…” (Separate each item in the array with a comma)

2. Mathematical operations commonly used in JS

  • % (brane) take the remainder
console.log(7 % 3); / / = > take more than 1
Copy the code
  • The battles:
    • All mathematical operations (if you encounter a non-numeric type, you need to cast it to a numeric type based on Number and then perform the operation)
  • The effect of addition:
    • Mathematical operations:
    • String concatenation:

String splicing

  • Definition: if a string appears on either side of the plus sign, it becomes string concatenation
  • Note: Before converting an object to a number, it needs to be converted to a string first. After converting an object to a string, it will be directly concatenated instead of converted to a number
  • Console. log(100 + true + 21.2 + null + undefined + ‘Tencent’ + [] + null + 9 + false); //==>NaNTencentnull9false
console.log(3 - "3px"); //=>NaN
console.log(3 + "3px"); //=>"33px" string splicing
console.log(1 + "1"); //=>"11" string stitching
console.log(1 + {}); //=>"1[object object]"; //=>"1[object object]
console.log(1 + []); / / = > '1'
console.log([10] + true); //=>"10true" converts [10] to a number first to the string "10", at which point the operation becomes string concatenation.
console.log(true + [10]); //=>"true10"
console.log(1 + true); / / = > 2

console.log(100 + true + 21.2 + null + undefined + "Tencent"+ + []null + 9 + false);
    100 + true= > 101
    101 + 21.2= >122.2
    122.2 + null= > 122.2
    122.2 + undefined= > NaN 
    NaN + "Tencent"= >"NaNTencent"String concatenation (all future string concatenation)"NaNTencent"+ [] = >"NaNTencent"
    "NaNTencent" + null= > "NaNTencentnull"
    "NaNTencentnull" + 9= >"NaNTencentnull9"
    "NaNTencentnull9" + false= > "NaNTencentnull9false"
Copy the code
  • Real projects often concatenate values of variables into a specified string
    // Complete string concatenation: 2020 March 03 12:00:00
    	let year = '2020';
    	let month = '03';
    	let day = '03';
    	let hours = '12';
    	let minutes = '00';
    	let seconds = '00';
    Copy the code
  • Traditional stitching
    • We need to concatenate variables into the string in a “++” or “++” fashion
    • Let result = year + ‘year’ + mouth + ‘month’ + day + ‘hour + ‘:’ + minutes + ‘:’ + seconds
    • This method involves a lot of disgusting rules, and it’s easy to misspell if you’re not careful
    // Get an element concatenation content from the page
    
     let str='<div class="box" id="box">';
     str+='

    '
    ; str+='<ul class="item">'; str+='<li></li>'; .Copy the code
  • Template string in ES6
    • The quotation marksThe ${}Backquotes: To solve problems in traditional string concatenationBack quotes ${} back quotesTo store variables or other JS expressions
    • Let result = backquotesFrom ${expressions using} ${year} ${day}, ${hours} : ${you} : ${seconds}The quotation marks
    • String concatenation can be done very easily
// Template strings in ES6 are designed to solve the problem of traditional string concatenation (the apostrophes above the TAB quotation mark) : ${} can be used to store variables or other JS expressions to easily concatenate strings
	let result = `${year}years${month}month${day}day${hours}:${minutes}:${seconds}`;
	console.log(result);
Copy the code
// Get an element concatenation content from the page

let str = ` < div class = "box" id = "box" > < h2 class = "title" > haha < / h2 > < ul class = "item" >The ${[10.20.30].map(item=>{
			return `<li>${item}</li>`;
		}).join('')}
	    </ul>
	</div>`;
	console.log(str); 
Copy the code

Mind mapping

3, Boolean

  • Contains:
    • true
    • false

1. Convert other data types to Boolean types

  • Methods:
    • Boolean([value])
    • ! [value] : Inverts the specified value after converting it to a Boolean type
    • !!!!! [value] : takes an inverse and takes an inverse again. This is equivalent to not taking an inverse but converting it to a Boolean value
  • Rules:
    • Only “0/NaN/null/undefined/ empty string” ends with false, the rest are true
    console.log(!!1); //=>true
    console.log(!1); //=>false
    
    console.log(!!- 1); //=>true
    console.log(!!0); //=>false
    console.log(!!undefined); //=>false
    console.log(!!Number('12px')); //=>Number('12px')->NaN false
    console.log(!! []);//=>true
    console.log(!!' '); //=>false
    console.log(!! {});//=>true
    Copy the code
  • Conditional judgment:
    /* Each condition must end with true/false */
        if (1= =1) {}
    	if (1) {
    		//=> write a value, also to convert the value to a Boolean, and then verify the program is true or false
    	}
    	if (3 + '3px') {} //=>3 + '3px' =>'33px' true
    	if (3 - '3px') {} //=>3 - '3px' =>NaN false
    Copy the code

Mind mapping

Null and undefined

  • Null Null object pointer
  • The application scenario of undefined

1, declare a variable, but do not assign a value, the variable is undefined;

var num;
console.log(num)===>undefined
Copy the code

2. If the property name of an object does not exist in the object, the value is undefined

var obj={name:"lili"};
    obj.name ====>"lili"
    obj.age====>undefined
Copy the code

3. If the function has a parameter, and we do not pass the parameter when executing the function, then print the parameter in the function body and the value will be undefined.

functionfn(n,m){ console.log(n); ====>undefined } fn()Copy the code

If the function does not return a value, the return value of the function is undefined. If the function does not return a value, the return value of the function is undefined.

function fn2(){

}
var res=fn2()  =====>undefined;
Copy the code