Knowledge supplement

arrar.map

The callback function is called once for each element in the array, in order. The return values (including undefined) from each callback are combined to form a new array.

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
 // Return element for new_array 
}[, thisArg])

var numbers = [1.4.9];
var doubles = numbers.map(function(num) {
  return num * 2;
});

// Doubles values are: [2, 8, 18]
// The numbers array is not modified: [1, 4, 9]
Copy the code

variable

/ Previously on /

/* shift+option+A */
// command+/

alert('Popup') | console.log('output') |cosole.error('wrong') | console.warn('warning') | prompt('Prompt message'.'Default value') |document.write('Output in page') * Variable name: letter | _ | $| number (cannot start) * Variable declaration is not assignedundefined
Copy the code

Numeric types

/ / blue* Integer/floating-point * octal:010---8^1x1+8^0x0=8* Hexadecimal:0xab---16^1x10+16^0x11=171* the value:Number. MAX_VALUE |Number.min_value (infinitely close to0It's smaller than that0) * infinite:Infinity| -Infinity

*NaN:isNaN(1) -false
/* Returns false*/ if it is a pure number
- isNaN('123');//false
- isNaN('123px');//true
- NaN= =NaN;// false -NaN is not equal to any number

var age=prompt('how old are you');
// The result of prompt is a string, in which case the isNaN judgment does not need to be used for implicit conversion
isNaN(age);
Copy the code

string

/ / black- Other types of data and character types are added to output values of character types - Prompt and input receive data of string typeCopy the code

String constancy

String constancy: A string cannot be modified * string all apis do not modify the string itself, but instead get a new string * Development usually declares a variable to receive the return value of a string method. These are primarily string apis that do not modify the original string but instead generate new string variable assignments: modify the data stored in the variable, regardless of constancylet str = 'I love you';

// This line of code does not modify the STR itself, but produces a new modified string
let res = str.replace('love'.'we');
console.log( res );// I like you
console.log( str );/ / I love you

// The string cannot be modified
str[3] = 'we';
console.log( str );// I love you

str = 'abc';
console.log( str );;;// ABC is a reassignment of a variable, regardless of string constancy
Copy the code

Escape character

Escape character explain
\n Newline character, n for newline
\ \ Slash \
‘single quotes
“Double quotation marks
\t TAB indent
\b A b b

Other types of

*boolean
/ / dark
trueParticipating operation when1Come to seefalseParticipating operation when0To see *undefined
/ / light grey
undefinedAdd them to the numbers and you end up with zeroNaN
undefinedAnd the result is a concatenated string *null
/ / light grey
nullYou add them to the numbers and you end up with the same numbernullAnd the result is a concatenated stringCopy the code

'' == null; // true, two different types of judgment will be converted to a number, "" is 0, null is 0, so equal

Determine type

var num=10;
console.log(typeof num); //number

var nl=null;
console.log(typeof nl);/ / object null objects

// The results obtained by typeOF are presented as strings
var a=10;
console.log(typeof (typeof a));//string

console.log(typeof 10+10)//number10
Copy the code

Data type conversion

Convert to string

- 1.Implicit conversion (+) - commonvar str=num + ' '

- 2.toString()
// Cannot convert undefined and null
var num=10;
// toString must be preceded by the name of the variable, not the value, (10.tostring ❌)
var str=num.toString();

- 3.String() - cast (not commonly used)// Can convert anything
var str=String(num);
Copy the code

Convert to a numeric type

- 1.Implicit conversion (- * / %)// % The number greater than its own is more than its own
10%11 = 10; ⚠ ️console.log(+num);
consolo.log(-(-num));

- 2.parseInt(string)
// If it is preceded by a number, it can convert the number before a non-number
parseInt('120px34');/ / 120
// If the first digit is not a number, it cannot be converted
parseInt('rem120px');//NaN
parseInt('true');//NaN
parseInt(true);//NaN

- 3.parseFloat(string)
// all parseInt except decimal

- 4.Number() - cast (not commonly used)Number('true');//NaN
Number(true);/ / 1
Number('120px');//NaN
Copy the code

Convert to Boolean

Boolean(a);// Null and negative values are converted to false
- ' '|0|NaN|null|undefined|false- note:' 'If there are Spaces in it, istrue
Copy the code

The operator

Increasing and decreasing

// prefix increment: ++num- Returns a value after adding// postincrementing: num++- First return the original value, then add/* same with */
Copy the code

Comparison operator

== If the two sides are different, both sides are converted to numerals

== tests only if values are equal (implicit conversions exist) === Both values and data types must be equalconsole.log(18= ='18');//true
console.log(18= = ='18'); //false
Copy the code

Logical operator

Short circuit operation (logical interrupt)

// The principle of short-circuit operation: when there are multiple expressions (values), when the left expression value can determine the result, the right expression value will not continue to calculate;

1.Logic and: expressions1&& expression2- Returns the expression if the value of the first expression is true2- Returns the expression if the value of the first expression is false1
console.log( 123 && 456 );/ / 456
console.log( undefined && null );//undefined

2.Logic or: expression1| | expression2- Returns the expression if the value of the first expression is true1- Returns the expression if the value of the first expression is false2
console.log( 123 || 456 );/ / 123
console.log( 'undefined' || ' ' );/ /"
Copy the code

Operator priority

- Parentheses () - unary operator ++ --! - after the first * / % + arithmetic operators - relational operators > > = < < = - equal operator = =! = = = =! = = - logical operators && before | | - the assignment operator = - the comma operator,Copy the code

Process control

If else if statement (multi-branch statement)

// It is suitable for checking multiple conditions.
ifConditional expression1) {statement1; }else ifConditional expression2) {statement2; }else ifConditional expression3) {statement3; . }else {
    // Execute this code if none of the above conditions are true
}
Copy the code

Ternary expression

expression1? expression2Expression:3;
Copy the code

Switch Branch flow control

switch(expression){case value1:
        // The code to execute when the expression equals value1
        break;
    case value2:
        // The code to execute when the expression equals value2
        break;
    default:
        // The code to execute when the expression is not equal to any value} ** Note: -switchThe value of the expression is the same as that of thecaseDo (===) comparison of the values ofcaseInside the statement when there is nobreak", proceed to the next stepcaseThe statement inside.// Example:
var grade=prompt('Enter your grades');
switch( parseInt(grade/10) ){ 
    case 10:
    case 9:
        alert('A');
        break;
    case 8:
        alert('B');
        break;
    case 7:
        alert('C');
        break;
    case 6:
        alert('D');
        break;
    default:
        alert('Fail');
}

//method2: Compares case values to switch values with true and false
var grade=prompt('Enter your grades');
switch( true) {case grade>=90:
        alert('A');
        break;
    case grade>=80:
        alert('B');
        break;
    case grade>=70:
        alert('C');
        break;
    case grade>=60:
        alert('D');
        break;
    default:
        alert('Fail');
}

Copy the code

cycle

for

For (){} the variables inside the parentheses are the same block-level scope


forInitialize a variable; Conditional expression; Operation expression){/ / the loop body
}
Copy the code

Double for loop

// Prints five rows and five columns of stars
var star = ' ';
for (var j = 1; j <= 5; j++) {
    for (var i = 1; i <= 5; i++) {
      star += 'do things'
    }
    // add a line break every time 5 stars are added
    star += '\n'
}
console.log(star); # Core logic:1.The inner loop prints five stars in a row2.The outer loop prints five linesCopy the code

The while loop

The conditional expression in the while must be a bool, and if it's not, it's automatically implicitly converted to bool

While (){} the variables inside the parentheses are different block-level scopes

// Boolean() go to false -> 0,NaN, "",null,undefined,false
// change to true -> change everything else to true
while(conditional expression) {// Loop body code
}
Copy the code

The do while loop

do {
    // Loop body code - Repeat the loop body code if the condition expression is true
} while(conditional expression);// It will be executed at least once
Copy the code

The continue and break

- continueThe keyword is used to immediately exit the loop and continue the next loopcontinueSubsequent code is executed one less time). -breakThe keyword is used to immediately jump out of the current entire loop (end of loop).Copy the code

An array of

Create an array

- 1.usingnewCreate an arrayvarArray name =new Array(a);var arr = new Array(a);// Create a new empty array

- 2.Create an array using an array literal//1. Create an empty array using array literals
varArray name = [];//2. Use array literals to create arrays with initial values
varArray name = ['white'.'black'.'rhubarb'.'rich'];
Copy the code
  • Note: If the array is accessed without an element corresponding to the index value, the value is undefined

The length of the array

#arr. Length - The length property of the array can be modified - if the length property is set to a value greater than the number of elements in the array, a blank element will appear at the end of the array; - If the length attribute is set to a value less than the number of elements in the array, the array elements exceeding that value will be removed// Insert a new element at the end of the arrayArray [array.length] = new data;Copy the code

Through the array

let arr=['London'.'CD'.'German'.'India'];
// The element of array
for(let city of arr){
  let str+=`${city}# `
}
console.log(str);// London#CD#German#India
Copy the code

function

A function may or may not have a return value

return

- in the use ofreturnStatement, the function stops execution and returns the specified value - if the function does notreturn, the return value isundefined

#break ,continue ,returnThe difference between -break: terminates the current loop body (e.gfor,while) -continue: Jumps out of the loop and continues with the next loop (e.gfor,while) -return: Can not only exit the loop, but also returnreturnStatement, and can also end the code inside the current functionCopy the code

arguments

Is a built-in object of the current function that stores all the arguments passed

argumentsThe presentation is a pseudo-array, so it can be traversed. Pseudo-arrays have the following characteristics: - Has the length attribute - stores data as an index - does not have array push, pop and other methods note: use this object inside the function, use this object to get the arguments passed during the function call.Copy the code

Two ways to declare a function

  1. Custom functions (named functions)

    /* Use the function keyword function to customize the function mode */
    
    // Declare the definition mode
    function fn() {... }/ / callfn(); - Also called named functions because of their names - the code that calls a function can be placed either before or after the declared functionCopy the code
  2. Function expression mode (anonymous function)

    // This is a function expression. Anonymous functions are terminated by semicolons
    var fn = function(){... };Function calls must be written under the function body fn();- This fn contains a function - function expression is the same as declaring variables - the code for a function call must be written after the function bodyCopy the code

scope

The use of scopes improves the locality of program logic, enhances the reliability of programs, and reduces name conflicts.

There are two types of scopes in JavaScript (pre-ES6) : global scope Local scope (function scope)

1.Global scope - Applies to the environment in which all code is executed (inside the entire script tag) or to a single JS file.2.Local scope - Applied to the code environment within a function, the local scope. It is also called function scope because it is related to functions.Copy the code

Scope of a variable

1.Global variables - variables declared under global scope - Note: Inside a function, variables that are not directly assigned are also global variables2.Local variables - variables declared in local scope - Note that function parameters can also be considered local variablesfunction fun(aru){
  var num1=10;Num1 is a local variable and can only be used inside functions
  num2=20;// Global variables
}
fun();
console.log(num1);// num1 is not defined
console.log(num2);/ / 20
consolo.log(aru);//aru is not defined

3.From the perspective of execution efficiency, global variables and local variables - global variables are only destroyed when the browser is closed, which takes up memory resources - local variables are destroyed when the function program is finished, which saves memory resourcesCopy the code

Block-level scopes (new in ES6)

- Block scope is included by {}. - In other programming languages (such as Java, C, etc.), inifA variable created in a statement or loop statement can only be created in thisif-js has no block-level scope (prior to ES6)if(true) {var num = 123;
  console.log(123); / / 123
}
console.log(123);   / / 123
Copy the code

The scope chain

An inner function can access an outer function variable and use a chain to determine which data can be accessed by the inner function. This is called a scope chain.

Take the nearest approach to finding the final value of a variable.

/ / case 1:
function f1() {
    var num = 123;
    function f2() {
        console.log( num );
    }
    f2();
}
var num = 456;
f1();/ / 123

Case 2: / /
var a = 1;
function fn1() {
    var a = 2;
    var b = '22';
    fn2();
    function fn2() {
        var a = 3;
        fn3();
        function fn3() {
            var a = 4;
            console.log(a); / / the value of the 4 a
            console.log(b); / / the value of b '22'
        }
    }
}
fn1();
Copy the code

Preliminary analysis

JavaScript parsers run JavaScript code in two steps: pre-parsing and code execution.

  • Preparse: In the current scope, variables with var and function declarations are pre-declared or defined in memory by default before JS code is executed.

  • Code execution: Execute JS statements from top to bottom.

    Pre-parsing completes the declaration of variables and functions before the code is executed.

Variable preresolution (variable promotion)

- Variable declarations are promoted to the top of the current scope, variable assignments are not promoted. - ** Variable promotion only promotes declarations, not assignments **console.log(num);  // undefined
var num = 10;      
/ / equivalent to
var num;
console.log(num); // undefined
num = 10; 

Copy the code

Function preparsing (function promotion)

- Function declarations are promoted to the top of the current scope, but the function is not called.1.Name the function fn();/ / 'print'
function fn() {
    console.log('print');
}
/ / equivalent to
function fn() {
    console.log('print');
}
fn();
// So it can be called normally


2.The anonymous function fun();// fn is not a function
var fun=function(){
  console.log(22);
}
/ / equivalent to
var fun;
fun();// The fun variable is only available, so an error is reported
fun=function(){
  console.log(22);
}
// This also explains why anonymous function calls must be written below
Copy the code

case

1 / / cases

f1();
console.log(c);
console.log(b);
console.log(a);

function f1() {
  	//var a=9; b=9; c=9; BC is viewed as a global variable
    var a = b = c = 9;
    console.log(a);
    console.log(b);
    console.log(c);
}
/ / equivalent to

function f1() {
  var a;
  a=9;
  b=9;
	c=9;
  console.log(a);/ / 9
  console.log(b);/ / 9
  console.log(c);/ / 9
}
f1();
b=9;
c=9;
console.log(c);/ / 9
console.log(b);/ / 9
console.log(a);// a is not defined
Copy the code

/Case 2/

function demo() {
    function demoSon() {
        num = 3;
        // If a variable is not directly assigned to the function, the function will look for the declaration of the variable layer by layer. If not, the variable can be used directly in the outer layer. Until the variable is declared at a certain level, it can only be used at that level, not at the next level.
        // The variable can only be used after the function is called
    }
    var num = 2;
    demoSon();
    console.log(num);

}
demo();
console.log(num);

/ / equivalent to
function demo() {
    function demoSon() {
        num = 3;
    }
    var num;
    num = 2;
    demoSon();
    num = 3;
    console.log(num);/ / 3

}
demo();
console.log(num);//num is not defined
Copy the code

object

1.What is an object? - In JavaScript, an object is an unordered collection of related properties and methods. Everything is an object, such as strings, numbers, arrays, functions, etc. - Objects are made up of properties and methods.2.Why do we need objects? - The disadvantage of storing data in arrays is that the data can only be accessed by index values. Developers need to know the ranking of all the data in order to accurately retrieve the data, and when there is a large amount of data, it is impossible to remember the index values of all the data. - Object for each data set attribute name, access to data more semantic, clear data structure, clear meaning, convenient for developers to use. - Object expression structure in JS is clearer and more powerful.Copy the code

There are three ways to create objects

1. Create object with object literals {}

var star = {
    name : 'pink'.age : 18.sex : 'male'.sayHi : function(){
        alert('Hello, everyone.'); }};1.Access the properties of the object: -console.log(star.name)     // Invoke the name attribute
- console.log(star['name'])  // Invoke the name attribute

2.Call the object's method - star.sayhi ();// Call the sayHi method with the following parentheses
Copy the code

/ Variable, attribute, function, method summary /

/* Attributes are part of an object, while variables are not. Variables are containers that store data separately- Attributes: Variables in an object are called attributes. They do not need to be declared and are used to describe characteristics of the object/* Methods are part of an object. Functions are not part of an object. Functions are containers that encapsulate separate operations */- Functions: exist separately and can be called by "function name ()". - Methods: The functions inside the object are called methods. Methods do not need to be declared. Methods describe the behavior and functionality of the object.Copy the code

2. Create an Object using new Object

- Creates an empty objectvar andy = new Obect();
/* Create an Object with the built-in constructor Object, and the Andy variable already holds the created empty Object */- Add attributes and methods to empty objects andy.name ='pink';
andy.age = 18;
andy.sex = 'male';
andy.sayHi = function(){
    alert('Hello, everyone.');
}
Copy the code

3. Use constructors to create objects

/ constructor /

Why use constructors? - Because the previous two methods can only create one at a time. #1.The definition of a constructor - is a special function used to initialize an object, that is, to assign initial values to its member variables. - it's always withnewOperators used together. - We can extract some common properties and methods from the object and encapsulate them in this function. #2.The wrapper format of the constructorfunctionConstructor name (parameter1The parameter2The parameter3) {
     this. The property name1= parameter1;
     this. The property name2= parameter2;
     this. The property name3= parameter3;
     this. Method name = function body; } #3.The format of the constructor callvar obj = newConstructor name (argument1That argument2That argument3)
/* Obj receives the object created by the constructor. * /# Note - Constructor convention ** uppercase **. - Attributes and methods in functions need to be preceded by **this**, representing the properties and methods of the current object. - The ** in the constructor is not requiredreturnReturns the result **. ** must be used when creating objectsnewTo call the constructor **. #4.Other - constructors, such as Stars(), abstract the common part of an object, encapsulate it in a function, and refer to a general class (class) - Creates objects, such asnew Stars(), especially one, passnewThe process of creating an object by keyword is also called object instantiationCopy the code

The difference between constructors and objects

1.Constructors generally refer to a class (star) similar to those in Javaclass2. Object refers to a specific thing (Andy Lau) 3.newThe process of creating an object is called instantiationCopy the code

The new keyword

# Execution process:1.newThe constructor creates an empty object in memory2.thisIt points to the empty object you just created3.Execute the code inside the constructor to add properties and methods to the empty object4.Return this object (so it is not needed in the constructorreturn) # Function:1.Before the constructor code begins execution, create an empty object;2.Modify thethisPoint to, turn tothisPoint to the created empty object;3.The code that executes the function4.After the function completes, returnthisThat is, the created objectCopy the code

this

When a constructor is used to create an objectthisPointing problem offunction Person(name,age){
			this.name=name;
			this.age=age;
			this.sayname=function(){
				alert(this.name);
			};
}
The constructor is actually a function called with the new operator. When we use new, the this inside the constructor points to the new instance, as in:
var p1=new Person('tom'.10);// This points to p1
alert(p1.name);// tom
p1.sayname();// tom

// Call directly (new not applicable)
var p2=Person('tom'.10);
alert(p2.name);// (error) name is undefined
p2.sayname();  Sayname is undefined

alert(name)//tom
sayname();//tom
Sayname = sayname; sayname = sayname;
alert(window.name);
window.sayname(); # Apparently notnewInstead of using a direct callthisInstead of representing the new instance P2window.thisPut name and sayName globallywindowIn the.Copy the code

Traverse object

for(variableinObject name) {// Execute the code here
}
/* The variable in the syntax is custom, it needs to conform to the naming convention, usually we write this variable as k or key. * /

for (var k in obj) {
    console.log(k);      // where k is the attribute name
    console.log(obj[k]); // obj[k] is the attribute value
}
Copy the code

Built-in objects

Antecedents feed

Objects in JavaScript are divided into3Types: custom objects, built-in objects, browser objects - the first two are JS base objects that are ECMAScript; - The third browser object is unique to JS - the built-in object provides some common or ** most basic and necessary functions ** (properties and methods), such asMath,DateArray,StringEtc. - Convenient for rapid developmentMDN: https://developer.mozilla.org/zh-CN/
Copy the code

The Math object

The Math object is not a constructor (new is not required); it has properties and methods of mathematical constants and functions.

Property, method name function
Math.PI PI
Math.floor() Take down the whole
Math.ceil() Take up the whole
Math.round() Note that the nearest rounded version is -3.5 and the result is -3
Math.abs() The absolute value
Math.max()/Math.min() Find the maximum and minimum
Math.random() Gets a random value in the range [0,1)

** Note: the above method must be used with parentheses

/Math.max()/

console.log(Math.max(1.99.'pink'));//NaN
console.log(Math.max());//-Infinity

// Encapsulate a mathematical object
var myMath={
  PI: 3.141592653.max: function(){
    var max=arguments[0];
    for(var i=0; i<arguments.length; i++){if(arguments[i]>max)
        max=arguments[i];
    }
    returnmax; }}console.log(myMath.PI)
Copy the code

/Math.abs()/

// There are implicit conversions that convert only numeric strings to numerals
console.log(Math.abs('1'));/ / 1
console.log(Math.abs('-120px'));// NaN
console.log(Math.abs('pink'));// NaN
Copy the code

/3 round methods /

// (1) math.floor () console.log(math.floor (1.1)); // (1) math.floor () console.log(math.floor (1.1)); / / 1
console.log(Math.floor(1.9)); / / 1

// (2) math.ceil () ceil ceiling rounded up to the maximum value
console.log(Math.ceil(1.1)); / / 2
console.log(Math.ceil(1.9)); / / 2

// (3) math.round (); // (3) math.round (); // (4) math.round ()
console.log(Math.round(1.1)); / / 1
console.log(Math.round(1.5)); / / 2
console.log(Math.round(1.9)); / / 2
console.log(Math.round(-1.1)); // -1
console.log(Math.round(-1.5)); // The result is -1
Copy the code

/Math.random()/

// Get random integers in the specified range, including these two integers:

function getRandom(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min; 
}

// Random roll call
var arr = ['Joe'.'Zhang SAN Feng'.'Crazy Guy'.'bill'.'Li Sisi'.'pink teachers'];
console.log(arr[getRandom(0, arr.length - 1)]);

/ / guess Numbers
var random=getRandom(1.10);
while(true) {var num=promt('You guess? Enter a number between 1 and 10 '.);
  if(num>random)
    alert('You can't believe it.');
  else if (num < random)
    alert(You guessed it was too small.);
  else 
    alert('You look good. You got it.');
    break; // Exit the entire loop terminator
}

Copy the code

The date object

Date is a constructor (requiring new), so it needs to be instantiated to use its specific methods and attributes.

- useDateInstantiate the date object// 1. If no argument is passed when creating the instance, the resulting date object is the date object corresponding to the current time
var now = new Date(a);// 2. Get the date object at the specified time
// The parameters are usually written as numbers (2019, 10, 01) or strings ('2019-10-1 8:8:8') or (2019/10/1).
var date1 = new Date(2019.10.1);
console.log(date1); // Return November instead of October
var date2 = new Date('the 2019-10-1 8:8:8');/ / the commonly used
console.log(date2);// Return to normal October
Copy the code

/Format date year month day/

var date=new Date(a);var year=date.getFullYear();// Return year 2019 of the current date
var month = date.getMonth() + 1;// Month returns month less than 1 month remember month +1
var dates = date.getDate();// What number is returned
var arr = ['Sunday'.'Monday'.'Tuesday'.'Wednesday'.'Thursday'.'Friday'.'Saturday'];
var day = date.getDay();// Returns 0-6 days of the week

console.log('Today is:' + year + 'years' + month + 'month' + dates + 'day' + arr[day]);
Copy the code

/Formatting dates in seconds/

// Encapsulate a function that returns the current minute-and-second format 08:08:08
function getTimer(){
  var time=new Date(a);var h = time.getHours();
  h = h < 10 ? '0' + h : h;
  var m = time.getMinutes();
  m = m < 10 ? '0' + m : m;
  var s = time.getSeconds();
  s = s < 10 ? '0' + s : s;
  return h+':'+m+':'+s;
}
console.log(getTimer);
Copy the code

/Gets the total number of millimeters of the date(Timestamp) /

/* Total number of milliseconds: the number of milliseconds based on January 1, 1970 (UTC) is unique and therefore also called a timestamp */

// Instantiate the Date object
var now = new Date(a);// 1. Get the original value of the object
console.log(date.valueOf());1 / / method
console.log(date.getTime());2 / / method
// 2
var now = + new Date(a);// Method 3 (common)
// 3. The method provided in HTML5 has compatibility issues
var now = Date.now();4 / / method
Copy the code

/Countdown sequence/

function countDown(time){
  var nowTime=+ new Data();
  var inputTime=+ new Data(time);
  var times=(inputTime-nowTime)/1000;// convert ms to s
  var d=parseInt(times / 60 / 60 / 24);/ / day
  d = d < 10 ? '0' + d : d;
  var h = parseInt(times / 60 / 60 % 24); / /
  h = h < 10 ? '0' + h : h;
  var m = parseInt(times / 60 % 60); / / points
  m = m < 10 ? '0' + m : m;
  var s = parseInt(times % 60); // The current second
  s = s < 10 ? '0' + s : s;
  return d + 'day' + h + 'when' + m + 'points' + s + '秒';
}
console.log(countDown('the 2021-5-22 21:30:00'));
Copy the code

The array object

There are two ways to create arrays

  • Literal mode

    var arr = [1."test".true];
    Copy the code
  • new Array()

    var arr = new Array();
    Copy the code

    Note: ArR creates an empty Array. If you need to use the Array constructor to create a non-empty Array, you can pass in parameters when creating the Array

    Parameter transfer rules are as follows:

    • If only one argument is passed, it specifies the length of the array

    • If more than one parameter is passed, the parameter is called the element of the array

      var arr1 = new Array(2);  // The 2 indicates that the array is of length 2 and contains 2 empty elements
      var arr1 = new Array(2.3); // This is equivalent to [2,3] to indicate that there are two elements in the array 2 and 3
      Copy the code

Check if it is an array

  • The instanceof operator

    • Instanceof determines whether an object is an instanceof a constructor

      var arr = [1.23];
      var obj = {};
      console.log(arr instanceof Array); // true
      console.log(obj instanceof Array); // false
      Copy the code
  • Array.isArray()

    • Array.isarray () is used to determine whether an object is an Array. IsArray () is a method provided in HTML5 (ie9 + supports).

      var arr = [1.23];
      var obj = {};
      console.log(Array.isArray(arr));   // true
      console.log(Array.isArray(obj));   // false
      Copy the code

Adds a method to delete an array element

  • There are methods for adding and deleting elements in the array. Some methods are listed in the following table.

Note: Push and unshift are methods for adding elements; Pop and Shift are methods to delete elements

// 1.push () adds one or more array elements to the end of our array (the original array also changes)
var arr = [1.2.3];
console.log(arr.push(4.'pink'));// Returns the length of the new array


// 2. Unshift adds one or more array elements to the beginning of our array.
console.log(arr.unshift('red'.'purple'));// Returns the length of the new array


// 3.pop () removes the last element of the array (the original array also changes)
console.log(arr.pop());// The result is the deleted element
// (1) pop is used to delete the last element of the array
// (2) pop() takes no arguments
 
  
// 4. shift() removes the first element of the array (the original array also changes)
console.log(arr.shift());// The result is the deleted element
Shift deletes the first element of the array. Remember that you can only delete one element at a time
// (2) shift() has no argument
Copy the code

Splice (delete/Add/replace)

The splice() method modifies an array by deleting or replacing existing elements or adding new ones in place, and returns the modified contents as an array. This method changes the original array.

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
Copy the code
  • start

    • Specifies the starting position of the modification (counting from 0).
    • If the length of the array is exceeded, the contents are appended from the end of the array.
    • If it is negative, it represents the number of bits from the end of the array (counting from -1, which means -n is the NTH element to the last and equivalent to array.length-n);
    • If the absolute value of a negative number is greater than the length of the array, the starting position is bit 0.
  • DeleteCount optional

    • An integer representing the number of array elements to remove.
    • If deleteCount is greater than the total number of elements after start, all elements after start are deleted (including the start bit).
    • If deleteCount is omitted, or its value is greater than or equal to array.length-start (that is, if it is greater than or equal to the number of all elements after start), then all elements in the array after start are deleted.
    • If deleteCount is 0 or negative, the element is not removed. In this case, at least one new element should be added.
  • item1, item2, … optional

    • The element to be added to the array starts at the start position. If not specified, splice() will delete only array elements.
  • The return value

    • An array of deleted elements. If only one element is removed, an array containing only one element is returned. If no element is deleted, an empty array is returned.
1.From the first2Bit start deletion0Element, insert "drum"var myFish = ["angel"."clown"."mandarin"."sturgeon"];
var removed = myFish.splice(2.0."drum");

// myFish: ["angel", "Clown ", "drum", "mandarin"," Sturgeon "]
// Deleted element: [], no element is deleted

2.From the first2Bit start deletion0Element, insert "drum" and"guitar"
var myFish = ['angel'.'clown'.'mandarin'.'sturgeon'];
var removed = myFish.splice(2.0.'drum'.'guitar');

// myFish: [" Angel ", "Clown ", "drum", "guitar", "mandarin"," Sturgeon "]
// Deleted element: [], no element is deleted

3.From the first3Bit start deletion1An elementvar myFish = ['angel'.'clown'.'drum'.'mandarin'.'sturgeon'];
var removed = myFish.splice(3.1);

// myFish: ["angel", "Clown ", "drum"," Sturgeon "]
// Deleted element: ["mandarin"]

4.From the first2Bit start deletion1Element, and insert "trumpet"var myFish = ['angel'.'clown'.'drum'.'sturgeon'];
var removed = myFish.splice(2.1."trumpet");

// 运算后的 myFish: ["angel", "clown", "trumpet", "sturgeon"]
// Deleted element: ["drum"]

5.From the first2Bit start deletion2An elementvar myFish = ['parrot'.'anemone'.'blue'.'trumpet'.'sturgeon'];
var removed = myFish.splice(myFish.length - 3.2);

MyFish: ["parrot", "Anemone "," Sturgeon "]
// Deleted element: ["blue", "trumpet"]

6.From the bottom of the first2Bit start deletion1An elementvar myFish = ['angel'.'clown'.'mandarin'.'sturgeon'];
var removed = myFish.splice(-2.1);

// myFish: ["angel", "Clown "," Sturgeon "]
// Deleted element: ["mandarin"]

7.From the first2Bit to begin removing all elementsvar myFish = ['angel'.'clown'.'mandarin'.'sturgeon'];
var removed = myFish.splice(2);

// myFish: ["angel", "Clown "]
// Deleted element: ["mandarin", "sturgeon"]
Copy the code

Array sort/flip

// 1. Flip the array
var arr = ['pink'.'red'.'blue'];
arr.reverse();
console.log(arr);

// 2. Array sort (bubble sort)
var arr1 = [13.4.77.1.7];
arr1.sort();// Only one digit

// Note: the sort method takes arguments to set ascending and descending sorts
arr1.sort(function(a, b) {
  // return a - b; Ascending order of arrangement
  return b - a; // The descending order
});
console.log(arr1);
Copy the code

Array index method

var arr = ['red'.'green'.'blue'.'pink'.'blue'];// It returns only the first index that meets the condition // it returns -1 if it cannot find an element in the array
console.log(arr.indexOf('blue'));/ / 2

//lastIndexOf(array element) returns the index number of the array element to start the search
var arr = ['red'.'green'.'blue'.'pink'.'blue'];
console.log(arr.lastIndexOf('blue')); / / 4
Copy the code

/ Array deduplicate case /

// Core algorithm: we iterate over the old array, then take the old array element to query the new array, if the element does not appear in the new array, we add, otherwise do not add.
function unique(arr) {
  var newArr=[];
  for(var i=0; i<arr.length; i++){if(newArr.indexOf(arr[i]) == -1){ newArr.push(arr[i]); }}return newArr;
}
Copy the code

Arrays are converted to strings

// 1.toString () converts our array to a string
var arr = [1.2.3];
console.log(arr.toString()); / / 1, 2, 3

// 2. Join (separator)
var arr1 = ['green'.'blue'.'pink'];
// Join if no arguments are passed, join elements according to ","
console.log(arr1.join()); // green,blue,pink
console.log(arr1.join(The '-')); // green-blue-pink
console.log(arr1.join('&')); // green&blue&pink
Copy the code

toString(16)

// Convert any number to hexadecimal
function getRandom(min, max) {
            min = Math.ceil(min);
            max = Math.floor(max);
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }

 function randomColor() {
     var color = The '#'
     for (var i = 0; i < 6; i++) {
         // num.tostring (16) converts numbers to hexadecimal
         color += getRandom(0.15).toString(16);
     }
     return color;
 }
Copy the code

Other methods

String object

All methods on a string do not modify the string itself and return a new string after each operation

Basic packing type

To make it easier to manipulate basic data types, JavaScript also provides three special reference types: String, Number, and Boolean.

A primitive wrapper type wraps a simple data type into a complex data type, so that the primitive data type has properties and methods.

// What's wrong with the following code?
var str = 'andy';
console.log(str.length);
Copy the code

Basic data types don’t have properties and methods, whereas objects have properties and methods, but this code can execute because

Js wraps basic datatypes into complex datatypes as follows:

// 1. Generate temporary variables to wrap simple types into complex data types
var temp = new String('andy');
// 2. Assign to the character variable we declared
str = temp;
// 3. Destroy temporary variables
temp = null;
Copy the code

Immutability of a string

The value inside is immutable, although it looks like it can change the content, but in fact, the address is changed, and a new memory space is opened in memory.

When reassigning a value to a string variable, the string stored before the variable is not modified. Reassigning a value to the string in memory will create space in memory. This feature is the immutable character of the string. Since strings are immutable, this can be an efficient problem when concatenating large numbers of strings (avoid this)

Return position by character

Example: Find the positions and times of all o occurrences in the string “abcoefoxyozzopp”

1.So let's look for the first o2.Then, as long as the result returned by indexOf is not -1Just keep looking for it3.Since indexOf can only find the first one, subsequent lookups take the second argument, the current index plus1To continue the searchfunction(str,a){
  var index=str.indexOf(a,0);
	var count=0;
	var s=[]
	while(index! = -1){
  	s.push(index);
  	index=str.indexOf('o',index+1);
  	count++;
	}
  return [s,count];
}
var str='abcoefoxyozzopp';
console.log(find(str, 'o'));
Copy the code

Returns characters based on position

// 1. CharAt (index) returns characters based on position
var str = 'andy';
console.log(str.charAt(3));//y
// Iterate over all characters
for (var i = 0; i < str.length; i++) {
  console.log(str.charAt(i));
}

CharCodeAt (index) returns the ASCII value of the corresponding index number. Purpose: Determine which key the user presses
console.log(str.charCodeAt(0)); // the 0 corresponding to a corresponds to the ASCII value 97

// 3. STR [index] H5
console.log(str[0]); // a
Copy the code

In the above method, the charCodeAt method returns the ASCII code corresponding to the character at the specified position. The ASCII code comparison table is as follows:

Case: Judge a string'abcoefoxyozzopp'The character that occurs most frequently in the1.Core algorithm: Use charAt() to traverse the string2.Stores each character to an object, or if the object does not have the property1+ if it exists1

3.Iterates through the object to get the maximum value and the character/* Note: in the traversal process, each character in the string is stored in the object as an attribute, corresponding to the number of occurrences of the character */

function countMax(str){
  var o={};
  var max=0;
  // Iterate over the string, recording the corresponding number of times for each string
  for(var i=0; i<str.length; i++){var chars=str.charAt(i);
    if(o[chars]){
      o[chars]++;
    }else{
      o[chars]=1; }}// Iterates through the object to find the most frequently occurring character and the number of occurrences
  for(var k in o){
    if(o[k]>max){ max=o[k]; m=k; }}return [m,max];
}
var str = 'abcoefoxyozzopp';
console.log(countMax(str));
Copy the code

String manipulation methods (emphasis)

// 1. concat(' string 1',' string 2'....) Concatenate multiple strings
var str = 'andy';
console.log(str.concat('red'));

// 2. Substr (' truncate starting position ', 'truncate several characters ');
var str1 = 'The spring breeze of reform blows all over the earth';
console.log(str1.substr(2.2)); // The first 2 is the index number of the 2 start from the second 2 is the number of characters
Copy the code

The replace () method

// 1. Replace character replace(' replaced character ', 'replaced character ') It only replaces the first character
var str = 'andyandy';
console.log(str.replace('a'.'b'));// bndyandy

// There is a string 'abcoefoxyozzopp' that requires all o's to be replaced with *
var str1 = 'abcoefoxyozzopp';
while (str1.indexOf('o')! = = -1) {
  // replace returns the new string. It does not change the string. It needs to be reassigned
	str1 = str1.replace('o'.The '*');
}
console.log(str1);
Copy the code

The split () method

// 2. Convert characters to array split(' separator ') We learned earlier that join converts an array to a string
var str2 = 'red, pink, blue';
console.log(str2.split(', '));// ['red','pink','blue']
var str3 = 'red&pink&blue';
console.log(str3.split('&'));
Copy the code

trim()

// Remove whitespace from both sides of the string
// If it is a space string, all Spaces are removed
var str=' ref ';
console.log(str.trim());//ref
Copy the code

Simple data types and complex data types

Simple data types

Simple types (basic data types, value types) : The value itself is stored in the variable during storage, including String, number, Boolean, undefined, null

// The simple datatype null returns an empty object
var timer = null;
console.log(typeof timer);

// If there is a variable that we want to store as an object later, and we don't know what to store, then we give it null
Copy the code

Complex data types

Complex data types (reference types) : Only addresses (references) are stored in variables during storage. Objects (system objects, custom objects) created by the new keyword, such as Object, Array, Date, etc.

The stack

  • Stack space allocation difference:

1. Stack (operating system) : the operating system automatically distributes and releases the parameter values and local variable values of the storage function. It operates like a stack in a data structure;

Simple data types are stored on a stack

2, heap (operating system) : store complex types (objects), generally allocated by the programmer to release, if the programmer does not release, by the garbage collection mechanism to recover.

Complex data types are stored in the heap

How data is stored

1.Simple data types (value types) are stored in the stack, which creates a space for value-value variables to be stored directly in the stack2.Complex data types are stored in a hexadecimal representation of the address on the stack and then the address refers to the data in the heap - reference type variables (stack space) store the address, and the actual object instances are stored in the heap spaceCopy the code

Simple type parameter passing

A function parameter can also be considered a variable. When we pass a value variable as a parameter to a function parameter, we are actually copying the value of the variable in the stack space to the parameter, so that any changes made to the parameter inside the method will not affect the external variable.

function fn(a) {
    a++;
    console.log(a); 
}
var x = 10;
fn(x);/ / 11
consoleLog (x);/ / 10
Copy the code

Copy the code

Parameter transfer for complex data types

A parameter of a function can also be treated as a variable. When we pass a reference to a type variable to a parameter, we are actually copying the stack address of the variable to the parameter. The parameter and the argument actually hold the same heap address, so we operate on the same object.

function Person(name) {
    this.name = name;
}
function f1(x) { // x = p, xp points to the same address
    console.log(x.name); // 2. Andy Lau
    x.name = Jacky Cheung;
    console.log(x.name); // 3. Jacky Cheung
}
var p = new Person("Andy Lau");
console.log(p.name);    // 1. Andy Lau
f1(p);
console.log(p.name);    // 4. Jacky Cheung
Copy the code

var a={
    name:'zs'
}
var b=a;
a.name= 'ls';
console.log(b.name);// ls
// Create a new space. The new address points to a new memory block
a = {
name:'ww';
}
console.log(b);// ls
Copy the code