I. Data type (6+1)
- Basic data types: undefined, NULL, Boolean, numbe, string, symbol
- Reference data type: object, which is subdivided into function, Array, Date, re, etc.
- Basic data types: They take up small space and are fixed in size. They are frequently used data and therefore stored in stacks.
- The base type is generally immutable, and when the value changes, the address changes, so instead of changing the original value, a new value is created.
- Reference data types are stored in both stack and heap, and reference data types are stored in
Pointer (variable name) stored in stack
, the pointer points toThe starting address of the entity in the heap (variable value)
. - Reference data type values can be changed based on the original value.
- When a reference datatype variable is copied, it copies the same pointer address and shares the same heap entity.
1.1 Basic data types
-
Typeof determines all value type data and returns strings
-
Common value types include: number, string, Boolean, undefined, symbol, return the corresponding type (lowercase).
-
Common reference types can be identified: Object,array,null. All objects are returned
-
Function returns function
1.undefined
- If a variable is not initialized after it is declared, it is undefined, which is the unique value;
- The special case is even if the variable a is not declared, typeof A; //undefined
2. The null type
-
Null Object pointer, represented by checking that typeof NULL returns ‘Object’;
-
Null initialization is recommended when defining objects to be saved in the future.
-
Null is a false value; So, null == undefined; To true.
-
=== === === === === ==
-
null==0 ; //false
-
! null==true; // True is used for if judgment
3.Boolean
All data types can be converted to Booleans. Data is converted to Boolean values: 0, NaN, null, and undefined are false, the rest are true
4.number
5.string
-
1. ToString (): There is no toString() method for all values except null and undefined, which returns a copy of the string.
-
2.String(): If you are not sure whether a value is null or undefined, you can use the String() function, which always returns a String of the corresponding type.
-
3. Use +” “: either the value to be converted + an empty string (” “), or the conversion can be implemented.
-
ES6’s new template literals are wrapped in backquotes to preserve newline characters, define strings across lines, and interpolate with ${}.
1.2 Object Reference data type
An Object is a collection of data and functions.
1.3 Implicit transformation
- 1 Converted to String —- 1. String concatenation (+) converted to String.
- 2. Convert to Number (math operation)– judge
Equal? More than?
, are generally converted into numbers for comparison - Boolean (if () {}, [],! Null is executed
1.4 Data Type Detection (four types)
1. Typeof basic data type detection
-
Typeof [val] returns the current value as a lowercase string, but does not detect null values of the basic type,typeof null =>”object” ;
-
Typeof cannot subdivide object data types and returns “object”;
2. (val) instanceof class
- Determines whether the current class is on the prototype chain of the tested data.
- For arrays, res, and objects, functions can be subdivided, but they cannot detect basic data types
xxx instanceof Object/Array/Function
Copy the code
3.constructor
[r]. Val constructor = = = class; Because the constructor that gets the instance actually gets the class to which it belongs, the judgment is more accurate
4.Object.prototype.toString.call([val])
- There is toString on the other built-in class primitives, but these are used to convert to strings. Only toString on the Object base class primitives is used to detect data types.
console.log(Object.prototype.toString.call(a));//[object Array]
Copy the code
1.5 How to Identify Arrays and objects? IsArray, Instanceof, constructor, toString
// Method 1: Use array.isarray () in ES6
Array.isArray([])//true
Array.isArray({})//false
// Method 2: through 'instanceof class' :
console.log({} instanceof Array)//false
console.log(['111'.'222'] instanceof Array)//true
// Method 3 :constructor
console.log([].constructor.name==='Array')//true
console.log({}.constructor.name==='Object')//true
/ / method 4: through the Object. The prototype. ToString. Call ()
Object.prototype.toString.call({}) //"[object Object]"
Object.prototype.toString.call([]) //"[object Array]"
Copy the code
2. Variable promotion
- The variable promotion mechanism does
Make variables used first, declared later
. Variables defined by var and function have variable promotion mechanisms. Var is declared first and then initialized. Function is declared and initialized together. - Var: can be defined repeatedly. Variable promotion; A single {} is still a global variable.
- Let: The same scope cannot be defined twice; There is no variable promotion; Fixed in a single {} are local variables.
- Const: Defines constants. Const only guarantees that Pointers do not change, so the basic data type cannot be modified. But reference data types can be modified,
- Let /const/function uses curly braces (except for functions) as a new block-level context. With this mechanism, you don’t need to build closures to store looped event bindings and the like when developing projects
Iii. Function execution process
- A list of operations (initialize this, parameter assignment, variable promotion, code execution) — Release the private context after execution (execute environment stack)
- If something in the current private context (typically a heap) is occupied by something outside the context, it is not released, forming an indestructible context. That’s closures.
3.1 Higher-order functions and closures
Higher-order functions have two forms :(1) if a function can take functions as arguments, it is called a higher-order function. (2) If the return value of a function is a function, it is a higher-order function.
3.2 the closure
- If one function’s scope (A) has access to A variable in another function’s scope (B), then we can consider the accessed function (B) to be A closure. It is usually implemented in nested functions.
- Closures extend the scope of variables. Scopes outside fn can access scopes inside FN
- Closure application 1
const li = document.getElementsByTagName("li");
for (var i = 0; i < li.length; i++) {
(function (i) {
li[i].onclick = function () {
console.log(i);
};
})(i);
}
Copy the code
3.3 Stack Memory
- Stack memory is the code execution environment stack, which is used to execute code and store values of primitive types (created variables are also stored on the stack).
- Stack memory has global execution context, private context formed by function execution, and block-level scope
- Heap memory: Used to store values of reference data types. Browsers place built-in properties and methods in a separate memory. We then store a pointer to it on the stack.
Heap memory destruction
If you run out of heap memory and want to free it, you can make the variable point to the null pointer object null.Stack memory destruction
Global stack memory: destroyed only when the page is closed Normally, the private stack memory created by a function is destroyed as soon as it completes execution, but it may not be destroyed immediately if it is a closure function.
Four. Some operators
4.1 Increase and decrease+ + I and i++
++ I is incrementing and then participating; I++ is going to evaluate and then increment
4.2 Equality and congruence
- === === === === === ==
4.3 logical operators | | (or), && (with),! (a)
Logic short circuit:
// And operations -- condition A && condition BIf condition A is not true, then condition A is returned. If condition A is true, regardless of whether condition B is true, condition B short circuit ---- is false. So as long as condition A is false, condition B will not be computed, and the combined result will be false/ / conditions A | B | conditionsIf condition A is true, then condition A is returned. If condition A is not true, condition B is returned regardless of whether condition B is true. Because in logic or operation, there is A logical short circuit: since the rule of logic or operation is true, so long as condition A is true, then condition B does not operateCopy the code
4.4 Residual/Extension Operators (…)
- The rest of the operator just uses three dots
.
Unpack items. You can unpack strings, arrays, objects. - The remaining parameters are stored in an array. The extension operator takes each item of an array apart
- 1.
Array copy
var arr = [1.2.3];
var arr2 = [...arr];
arr2.push(4);
console.log(arr, arr2);//[1, 2, 3] [1, 2, 3, 4]
Copy the code
- 2.
Connect the array
var arr1 = [0.1.2];
var arr2 = [3.4.5];
//var arr3 = arr1.concat(arr2); Same as the following
var arr3 = [...arr1, ...arr2];
/ / orArr1. Push (... Arr2)Copy the code
- 3. Function calls use expansion syntax to expand arguments.
- 4. As residual arguments – When the number of arguments to a function is greater than the number of parameters, we can add the extra arguments to an array
.
- 5. Convert an Array of classes into a real Array — a collection of elements, a list of arguments, etc.
Logical structure-if, switch, while, do… while… , the for
- 1. If is used for interval judgment;
- 2. Enumerable fixed values can be judged by switch;
let day = 7;
switch (day) {
case 1:
console.log("Week 1");
break;
case 2:
console.log("Week 2");
break;
case 3:
console.log("Three weeks");
break;
default:
console.log("Other");// Execute this to print other
break;
}
Copy the code
- 3.
While loop syntax -- Find anything between 0 and 100 divisible by 7
while(condition expression){the statement whose condition satisfies the execution; }Copy the code
- 4.
do... The while loop
Enter the password for authentication
do{code that needs to be executed repeatedly; }while(conditional expression);// The body of the loop is executed once regardless of whether the conditional expression is true
let pwd;
do {
pwd = prompt("Please enter the correct password");
} while(pwd ! = ="123456");
alert("Welcome back.");
Copy the code
- 5.
The for loop
1.forLoop formatforInitialize the expression; Conditional expression; Post-loop delta expression){code that needs to be executed repeatedly; }2.forCharacteristics of cyclesforCyclic characteristics andwhileThe same characteristic of a loop is that the body of the loop is executed only if the conditional expression is true3.forThe execution flow of the cycle3.1The initialization expression is executed first and only once3.2Determines whether the conditional expression is true, and if so, executes the body of the loop3.3After executing the body of the loop, the post-loop increment expression is executed3.4repeat3.2~3.3, until the conditional expression is not trueCopy the code
/ / equilateral triangle
for (let i = 0; i <= 5; i++) {
for (let j = 0; j < i; j++) {
document.write("❤");
}
document.write("<br />");
}
/ / nabla
for (let m = 0; m < 6; m++) {
for (let n = m; n < 6; n++) {
document.write("❤");
}
document.write("<br />");
}
Copy the code
99 tables,
// The inner loop controls the display of each line
for (let i = 1; i < 10; i++) {
for (let j = 1; j <= i; j++) {
document.write(`${j}x${i}=${i * j}    `);
}
document.write("<br />");
}
Copy the code
Array Array
- An array is a collection of ordered data, each of which is called an element. An array can hold elements of any type.
- The index of the array starts at 0, and the length of the array starts at 1.
- The index of an array is used to get the item
arr[index]
The length of the array can be used to traverse the array, adding or removing elements at the end of the array.
6.1 Four methods for creating an array
- 1. Literal notation
- 2. Constructor method
- 3.Array.from() converts an array-like or iterable to an Array
- 4.Array.of(0, 2, 4, 6, 8)); // [0, 2, 4, 6, 8] can convert a set of parameters to an array instance
6.2 Four array detection methods
- 1.Array.isArray(arr)
- 2. Instance the Instanceof class
- 3.constructor
[].constructor.name==='Array'
- 4.
Object.prototype.toString.call(arr)
// [object Array]
6.3 Add, delete, modify and check
6.3.1 Adding five subscripts (subscript, Push, unshift, Splice, concat)
let array=[1.2.3.4.5]
//1. Increment by subscript
array.[array.length]=6
// 2.array.push () is added from behind
array.push("a"."b");
//3. Unshift () before array
array.unshift('0')
//4. Splice (a,b,5,6,78,9
// Delete b elements after the a element and add the rest to the array. A is index
/ / 5. Concat splicing
var arr = ['a'.'b'.'c'];
var arr2 = arr.concat('d'.1.2['e'.3]);
console.log(arr2); // ["a", "b", "c", "d", 1, 2, "e", 3]
Copy the code
6.3.2 Deleting four Types (POP, Shift, Slice, splice)
var arr = ["a"."b"."c"."d".1.2];
// the 1.pop() method removes the last item of the array and returns the deleted item.
let de = arr.pop();
//2.shift() deletes the first item of the array and returns the deleted item
arr.shift();
//3. Use slice(a,b) to slice multiple arrays without operating on the original array
// cut from index A to index B, including a but not including b
//4. Use the splice() method to specify the location to delete
//splice() can insert new elements at the same time as deleting them.
// Pass in three arguments: the starting position, the number of elements to delete, and any number of elements to insert;
//
var arr = [1.2.3.4.'a'.'b'.'c'];
var arr2 = arr.splice(2.2);// Select * from index where index = 2
console.log(arr); // [1, 2, "a", "b", "c"]
console.log(arr2); / / [3, 4]
Copy the code
6.3.3 Changing an Array One way — the splice() method changes an array
Splice (a, b, 1,2,3,4) deletes b elements starting with the element whose index is a, adds the following elements, and returns
6.3.4 Querying arrays (Index lookup, indexOf, Include, Find, findIndex, slice)
In addition to querying arrays with raw index numbers, JS provides many methods to query arrays
let arr=[1.2.3.4]
/ / 1. The index query
//arr[0], arr[1], arr[arr. Length-1]
/* 2. IndexOf () returns the first index in the array (starting from 0); . There are two arguments, the first is the element to be found; The second is where to start the search (the index value). LastIndexOf () finds */ from back to front
var array = [2.5.9];
array.indexOf(2); / / 0
array.indexOf(7); // -1
array.indexOf(9.2); / / 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); / / 0
//3. include() indicates whether there is such an item in the array and returns true or false
var num = [10.20.30.40.50.60.70.80.90];
var newNum7 = num.includes(40);
var newNum8 = num.includes(40.5);// look backwards from index 5
console.log(newNum7);//true
console.log(newNum8);//false
/* 4. Find () returns the first item that meets the criteria. The function takes three arguments: value, index, return, ruturn returns true, find returns */
var inventory = [
{ name: "apples".quantity: 2 },
{ name: "bananas".quantity: 0 },
{ name: "cherries".quantity: 5},];function findCherries(value, index, item) {
// console.log(value, "array current value ");
// console.log(index, "current item index ");
// console.log(item, "array itself ");
return value.name === "cherries";
}
console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }
// 5.findIndex () returns the first index in the array that meets the criteria (starting from 0). Use the same as find
//6. Use the slice() method to extract the array data:
var arr = [1.2.3.4.5.6];
var arr2 = arr.slice(-3);
console.log(arr); // [1, 2, 3, 4, 5, 6]
console.log(arr2); / / [4, 5, 6]
Copy the code
6.4 Sorting (Reverse, sort)
1. Flip the array
Array.reverse() : Reverses the position of the elements in an Array and returns the Array. This method changes the original array
2. Sort by size
- Sort takes a function argument and the function takes two values a, b; If the function returns a-b, the order is positive; if the function returns b-a, the order is reversed (from large to small); sort changes the array and returns the processed array
let a=[2.1.5.7.21.12.33.46.64.0.2.7.8]
a.sort((a,b) = >a-b)/ / ascending
a.sort((a,b) = >b-a)/ / descending
Copy the code
6.5 Other Methods
6.5.1 Array concat ()
Used to merge two or more arrays. This method does not change an existing array, but returns a new array.
let array=[10.20.30.40];
let array1=[50.60];
console.log(array.concat(array1));//[10, 20, 30, 40, 50, 60]
var arr = ['a'.'b'.'c'];
var arr2 = arr.concat('d'.1.2['e'.3]);
console.log(arr2); // ["a", "b", "c", "d", 1, 2, "e", 3]
Copy the code
6.6 Array.splice() Add, Delete, or modify
- Delete => You can delete any number of items by specifying
Two parameters
,Delete the location of the first item
And toNumber of items deleted
- Insert => You can insert any number of items into the specified location as long as you provide
Three parameters
, starting position, 0, the item to insert. If you want to insert more than one item, you can pass in the NTH item, the NTH +1 item… - Replace => to specify the location
Insert any number of items
And at the same timeDelete any number of items
, simply specify three parameters, the starting position, the number of items to delete, and any number of items to insert. The number of items to insert does not have to be the same as the number of items to delete
6.7 Array. The join ()
The join() method joins all the elements of an array (or an array-like object) into a string and returns the string. If the array has only one item, that item is returned without a delimiter.
var a = ['Wind'.'Rain'.'Fire'];
var myVar1 = a.join(); // The value of myVar1 changes to "Wind,Rain,Fire"
var myVar4 = a.join(' '); // myVar4 changes to "WindRainFire"
Copy the code
6.8 Array Iteration (5 types)
1.Array.every() checks if all conditions are met, and returns true
Array.every((item,index, Array)=>item>10) : Runs the given function on each item in the Array, and returns true if the function returns true for each item.
2.Array.some() returns true if there are any
Array.some((item,index, Array)=> conditional) : Runs the given function on each item in the Array, and returns true if the function returns true for any item
3.Array.filter() filters out arrays that meet the criteria
Array.filter((item,index, Array)=> conditional statement) : Returns an Array of items that return true by running the given function on each item in the Array.
let arrays = [11.22.3.4.5.4.3.2.1];
let everyResult = arrays.filter((item, index, array) = > {
return item > 10;
});
console.log(everyResult); [11.22]
Copy the code
4. Array.foreach () returns no value but executes on each element — it can be done in batches
Array.foreach ((item,index, Array)=>{operate on Array}) : The forEach() method performs the given function once on each element of the Array, returning no value.
let arrays = [
{
name: "cc"}, {name: "aa",},]; arrays.forEach((item, index, array) = > {
item.time = new Date(a); });console.log(arrays);
Copy the code
5.Array.map () does the same for all items in the Array and returns a new Array
Array.map((item,index, Array)=> Manipulate Array) : Runs the given function on each item in the Array and returns the Array returned as a result of each function call
let arrays = [1.2.3.4.5.4.3.2.1];
let mapResult=arrays.map((item,index,array) = >{
return item*2;
})
console.log(mapResult);/ / 2,4,6,8,10,8,6,4,2
Copy the code
The Array merging method array.reduce (total,current) can be used as an accumulator
Take two arguments: the first is the previous item and the second is the current item
let arrays = [1.2.3.4.5.4.3.2.1];
let sum = arrays.reduce((total, current) = > {
return total + current;
});
console.log(sum);
Copy the code
Es6 New array method
1) Array) of () and Array. The from ()
- Array.of always returns an Array of parameter values. If there are no arguments, an empty array is returned.
Array.of(1.2.3.4);/ / [1, 2, 3, 4]
Copy the code
- Array.from() converts array-like and iterable objects into arrays.
Common array-like objects: NodeList collection, arguments objects inside functions, iterable objects terator interface: string and Set structures
2. Array.copywithin () fills the Array and array.fill () replaces it in batches
The array.fill () method fills a fixed value to the specified position in the Array, taking the following arguments:
- Value: indicates the value to be filled
- Start: indicates the starting point for filling
- End: The end of the fill (index not included), if star and end are the same fill failed
[1.2.3].fill(4.1); / / [1, 4, 4]
[1.2.3].fill(4.3.3); / / [1, 2, 3]
Copy the code
3.Array.find() and array.findIndex () and array.includes ()
Array deep copy
- Method 1: original
Array.prototype.mySlice = function () {
const arrNew = [];
for (let i = 0; i < this.length; i++) {
arrNew.push(this[i]);
}
return arrNew;
};
var array = [1.2.3.4.6];
var arrayNew = array.mySlice();
Copy the code
- Concat concates the array and returns the new value
const array = [1.2.3.4.6];
const arrayNew = array.concat();
Copy the code
- Method 3: Slice an array and return the truncated value
const array = [1.2.3.4.6];
const arrayNew = array.slice();
Copy the code
- Method 4: Extend the operator
const array = [1.2.3.4.6];
const arrayNew = [...array];
/ / or
var arr1 = [1.2.3];
var [...arr2] = arr1;
Copy the code
Array maximum
- Method 1: original
let arr = [3.5, -2.7.4];
let max = arr[0];
for(let i = 1; i < arr.length; i++){
if(arr[i] > max){ max = arr[i]; }}console.log(max);
Copy the code
- Method 2 :sort the array from largest to smallest
const arr1 = [66.31.2.68.3.66];
let max = arr1.sort((a, b) = > b - a)[0];
console.log(max);
Copy the code
- ForEach () : select item from forEach() and assign it
const arr1 = [66.31.2.68.3.66];
let max = arr1[0];
arr1.forEach(function (item, index, arr1) {
if(item > max) { max = item; }});console.log(max);
Copy the code
- Method 4: Use math.max()
let arr = [3.5, -2.7.4];
let max = Math.max(... arr);// let max = Math.max.apply(Math, arr); // This or Math in Max
console.log(max);
Copy the code
Array to heavy
- ForEach () looks through each item in the array to see if there is an item in the array. If not, add it to the array.
let arr = [3.5, -2.7.4.4.6.5.3];
const arrUnique = [];
arr.forEach((item) = > {
if (arrUnique.indexOf(item) === -1) { arrUnique.push(item); }});console.log(arrUnique);
Copy the code
- 2.
Sort first in deweight
— Sort the original array, compare it with the neighboring array, and store it to the new array
let arr = [3.5, -2.7.4.4.6.5.3];
const arrUnique = [];
arr.sort((a, b) = > b - a);
arrUnique.push(arr[0]);
arr.reduce((pre, cur) = > {
if(pre ! == cur) { arrUnique.push(cur); pre = cur; }return pre;
});
console.log(arrUnique);
Copy the code
- 3. Object attribute de-duplication (recommended)
Each time the elements of the original array are assigned as the object’s property names, the object methods access these property names and assign them to the array. Finally, the string is removed with a map
arr = [1.7.4.5.3.4.5.6.8.6.9.6.5.6.4.6.67.7];
arrUnique = {};
arr.forEach((item, index) = > {
arrUnique[item] = "CAI Xukun";
});
arrUnique = Object.keys(arrUnique);
arrUnique = arrUnique.map((item) = > ~~item);
console.log(arrUnique);
Copy the code
- 4. Subscript for+indexof
function arrUnique(arr) {
let uni = [arr[0]].for (let i = 1; i < arr.length; i++) {
if (uni.indexOf(arr[i]) === -1) { uni.push(arr[i]); }}return uni;
}
Copy the code
- 5. Set implementation in ES6 (most commonly used in ES6)
function arrUnique(arr) {
arr = new Set(arr);
arr = Array.from(arr);
return arr;
}
Copy the code
- Es6 filter() and indexOf()
function arrUnique(arr) {
let arrNew = arr.filter((item, index) = > arr.indexOf(item) === index);
If the value is equal, add it to the array. If the value is not equal, there is another item that is the same as the current item. The current item should not be added
return arrNew;
}
Copy the code
- 7. Iterate through the array,
includes
Checks if the current item is iterated over in the new array, and adds to the new array if it does not
function arrUnique(arr) {
const arrNew = [arr[0]].for (let i = 0; i < arr.length; i++) {
if (!arrNew.includes(arr[i])) {
arrNew.push(arr[i]);
}
}
return arrNew;
}
Copy the code