Front end day 6 array / function / common built-in object / pre parsing / object / error

1. Array

1. Why learn arrays

For the previously learned data type, only one value can be stored (for example, Number/String).

If we want to store the names of all students in the class, how should we store them?

2. Definition of array

The so-called array is to arrange multiple elements (usually of the same type) in a set in a certain order. Then this set is called array.

Array is an ordered list, which can store any data in the array, and the length of the array can be adjusted dynamically.

3. Create an array from an array literal

// Create an empty array
var arr1 = []; 
// Create an array of 3 values with multiple array items separated by commas
var arr2 = [1, 3, 4]; 
// Create an array of 2 strings
var arr3 = ['a', 'c']; 
​
// You can get the length of the array through the length property of the array
console.log(arr3.length);
// You can set the length attribute to change the number of elements in the array
arr3.length = 0;

4. Get array elements

Value of array

[0] is the first element in the array. [1] is the second. The array index starts at 0.

// Format: array name [subscript] subscript is also called index
// Function: get the value of the subscript corresponding to the array. If the subscript does not exist, return undefined.
var arr = ['red', 'green', 'blue'];
arr[0]; // red
arr[2]; // blue
arr[3]; // The maximum subscript of this array is 2, so undefined is returned

5. Traversal array

Traversal: throughout all, each element of the array is accessed once, which is called traversal.

Basic syntax of array traversal:

for(var i = 0; i < arr.length; i++) {
    // Fixed structure of array traversal
}

6. New element in array

Assignment of array

// Format: array name [subscript / index] = value;
// If the subscript has a corresponding value, the original value will be overwritten. If the subscript does not exist, an element will be added to the array.
var arr = ["red", "green", "blue"];
// Replace red with yellow
arr[0] = "yellow";
// Added a new value of pink to the array
arr[3] = "pink";

push method of array

// Format: array name (. Push)
// If the subscript has a corresponding value, the original value will be overwritten. If the subscript does not exist, an element will be added to the array.
var arr = ["red", "green", "blue"];
arr.push("pink");
  1. Array case

(1) . cases

Find the sum and average of all numbers in a group

  var sum1 = 0;

  for (var i = 0; i < arrNum.length; i++) {

    sum1 += arrNum[i];

  }

  console.log(sum1);//338

  //  average value

  var abg = sum1 / arrNum.length;

  console.log(abg.toFixed(2));



Find the maximum and minimum values in a group of numbers and their location

  var numMax = arrNum[0];//Assume that the first element is the maximum

  var numMin = arrNum[0];//Assume that the first element is the minimum

  var indexMax = 0;

  var indexMin = 0;

  for (var i = 0; i < arrNum.length; i++) {

    if (arrNum[i] >= numMax) {

      numMax = arrNum[i];

      // console.log(i);

      indexMax = i + 1;

    }

    if (arrNum[i] <= numMin) {

      console.log("Ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah")

      numMin = arrNum[i];

      indexMin = i + 1;

    }

  }

  console.log("The maximum value is:" + numMax + ",Yes" + indexMax + "Elements!");

  console.log("The minimum value is:" + numMin + ",Yes" + indexMin + "Elements!");



Use string array|Or other symbols to return a string

  var str = "";

  var arrStr = ["I", "Guys", "yes", "good", "Child", "son"];

  console.log(arrStr);

  for (var i = 0; i < arrStr.length; i++) {

    console.log(arrStr[i]);

    // str = str + arrStr[i] + "|";

    if (i < arrStr.length - 1) {

      str = str + arrStr[i] + "|";

    } else {

      str = str + arrStr[i];

    }

  }

  console.log(str);

  console.log(typeof str);



It is required to remove the 0 items in the array, store the values that are not 0 into a new array, and generate a new array

  var newArr1 = [];

  for (var i = 0; i < arrNum.length; i++) {

    if (arrNum[i] != 0) {

      // console.log(arrNum[i]);

      newArr1.push(arrNum[i]);

    }

  }

  console.log(newArr1);



  //  5. Flip array

  var newArr2 = [];

  for (var i = arrNum.length - 1; i >= 0; i--) {

    console.log(arrNum[i]);

    newArr2.push(arrNum[i]);

  }

  console.log(newArr2);

3. Function

(1) Why should there be a function

If you want to find the sum of all numbers between 1-100 in multiple places, what should you do?

(2) What is a function

Encapsulate a relatively independent code block with specific functions to form an independent entity, that is, function.

A name (function name) can be called repeatedly in subsequent development.

The function encapsulates a piece of code that can be reused in the future.

(3) Definition of function

Function declaration

function Function name(){
  // Function body
}

Function expression

var fn = function() {
  // Function body
}

After the function is defined, the function body will not be executed, only when the function is called. Functions are generally used to do one thing. You need to use verbs + nouns to mean doing one thing, tellStory sayHello, etc.

(4) . function call

Syntax of calling function

Function name ();

Features: the function body can only be executed when calling. The call needs to be called by (). It can be called multiple times (reuse)

Code example

// Declarative function
function sayHi() {
  console.log("Did you eat?");
}
// Call function
sayHi();
​
// Find the sum of all numbers between 1 and 100
function getSum() {
  var sum = 0;
  for (var  i = 0; i < 100; i++) {
    sum += i;
  }
  console.log(sum);
}
// call
getSum();

(5) Parameters of function

Why have parameters

function getSum() {
  var sum = 0;
  for (var i = 1; i <= 100; i++) {
    sum += i;
  }
  console.log();
}
// Although the above code can be called repeatedly, it can only calculate the value between 1-100
// What if you want to calculate the sum of all numbers between n-m?

Syntax:

// The inside of a function is a closed environment. External values can be passed to the inside of a function by means of parameters
// Function declaration with arguments
function Function name(Formal parameter 1, Formal parameter 2, Formal parameter...){
  // Function body
}
// Function call with arguments


Function name (argument 1, argument 2, argument 3);

Formal and argument

1. Formal parameter: when declaring a function, in order to make the function more flexible, some values cannot be fixed. For these fixed values, we can set parameters for the function. This parameter has no specific value and only plays a role in occupying position. We usually call it formal parameter, also known as formal parameter.

2. Actual parameters: if the formal parameters are set when the function is declared, the corresponding parameters need to be passed in when the function is called. We call the passed in parameters as actual parameters, also known as actual parameters.

var x = 5, y = 6;
fn(x,y); 
function fn(a, b) {
  console.log(a + b);
}
//x. The Y argument has a specific value. When the function is executed, it will copy X and y to a and b inside the function. The internal value of the function is the new value copied, and the external X and y cannot be modified
  1. Function case

(1) . function cases

function getSum(n,m){

      var sum = 0;

      for (var i = n;i <= m;i++){

          sum += i;

      }

      console.log(sum);

    }

    getSum(1,100);//1-100

    getSum(50,100);//50-100

    getSum(2,100);//2 -100



function getArea(r){

      //  Math objects: Math

      console.log(Math);

      var area = Math.PI * r * r;

      console.log(area.toFixed(2));

    }

    getArea(10);



 function getMaxNum(m,n){

      if (m > n){

        console.log("Maximum:"+ m);

      }else if (m < n) {

        console.log("Maximum:"+ n);

      }else {

        console.log( m +"And"+ n + "equal");

      }

    }

    getMaxNum(150,150);

    getMaxNum(0,12);

5. Return value of function

(1) What is the return value

When the function is executed, it is not necessary to print the result all the time. We expect the function to give me some feedback (such as the return of the calculation result for subsequent operations). At this time, the function can return something, that is, the return value. The function returns a return value through return.

Return value syntax:

/

/Declare a function with a return value
function Function name(Formal parameter 1, Formal parameter 2, Formal parameter...){
  //Function body
  return Return value;
}
​//You can receive this return value through a variable


var   variable  =  Function name (argument 1, argument 2, argument 3);

The result of function call is the return value, so we can directly operate on the result of function call.

(2) . return value summary

1. If the function does not use the return statement, the function has the default return value: undefined

2. If the function uses a return statement, the value following return becomes the return value of the function

3. If the function uses a return statement, but there is no value after return, the return value of the function is: undefined

4. After the function uses the return statement, the function will stop and exit immediately after executing the return statement, that is, all other code after the return will not be executed.

The recommended approach is to either have the function always return a value or never return a value.

 function getJie(n){

      var jie = 1;

      if(n==0){

        return 1;

      }

      for(var i=1;i<=n;i++){

        jie *= i;

      }

      return jie;

    }

    var jiecheng =getJie(7);

    console.log(jiecheng);

Other functions

  1. . naming of functions

rule

1. It is composed of letters, numbers, underscores and $symbols, and cannot start with a number
     2. It cannot be a keyword or reserved word, such as for,while,this, name
     3. Case sensitive
standard
     1. The function name must be meaningful
     2. Observe the hump naming method
     3. It is not recommended to use $as the function name

  1. Coverage of functions

If both functions are function declarations and the function names are the same, the latter function will overwrite the previous one

function fn1() {

    console.log("Function declaration");

  }

  function fn1() {

    console.log("I'm the second fn1");

  }

fn1();//I'm the second fn1

If both functions are function expressions and the function names are the same, the function call will call the nearest one

 

 var fn2 = function () {

    console.log("First function expression fn2");

  } 

  fn2();//First function expression fn2

var fn2 = function () {

    console.log("I'm the second fn2 expression");

  }
  1. Built in object of function

In JavaScript, the arguments object is a special object, which is actually a built-in attribute of the current function. That is, all functions have a built-in arguments object, which stores all the arguments passed. Arguments is a pseudo array, so it can also be traversed.

The first few elements in the arguments array are arguments to the function

callee attribute: the function itself

callee.name: the name of the function

length attribute: number of arguments

callee.length: number of formal parameters

  1. , anonymous function

Anonymous function: a function without a name

How to use anonymous functions?

Anonymous functions cannot be executed through direct calls, so they can be executed through self calls of anonymous functions

(function () {
   alert(123);
  })();
  1. , function is a data type

Functions are reference data types

<script>

//1. You can type of

function run(){

}

console.log(typeof run)//function
  1. , function as parameter

Because a function is also a type, you can pass a function as an argument

function fnNum1(x) {

    console.log(x);

    x();

  }

 fnNum1(function () { console.log("Function is passed in as an argument") });

Because a function is a type, it can be inverted as an argument

 function fnNum2(x) {

    return x

  }

  // var num1 = fnNum2(120);

  var num1 = fnNum2(function () { console.log("Function as an argument") });

  console.log(num1);

  num1();

2. Pre analysis

Before interpreting and executing the JavaScript code, the JavaScript engine will pre parse the JavaScript code. In the pre parsing stage, the statement blocks starting with the keywords var and function will be processed in advance.

The key question is how to deal with it?

When the declaration of variables and functions is at the back of the scope, the declaration of variables and functions will be promoted to the beginning of the scope.

(1) . function promotion

func();

function func(){

alert("Funciton has been called");

}

Due to the pre parsing mechanism of JavaScript, the above code is equivalent to:

function func(){

alert("Funciton has been called");

}

func()

(2) . variable promotion

After reading the function declaration promotion, let's take another example of variable declaration promotion

alert(a);

var a = 1;

Due to the pre parsing mechanism of JavaScript, the value from alert in the above code is undefined. If there is no pre parsing, the code should directly report an error a is not defined instead of outputting the value. Doesn't it mean to advance? It's not supposed to alert 1. Why is it undefined?

So what we call ascension is a declared ascension.

Then looking back, the above code is equivalent to

var a; //Here is the statement

alert(a);//There are no initialization and assignment operations after variable declaration, so this is undefined

a = 1

Therefore, the promotion of variables is only the promotion of declarations

(3) Function with the same name

Through the contents of the previous section, we have a basic understanding of variable and function declaration promotion. Then, let's analyze some slightly complex situations.

Look at the following code

func1();

function func1(){

console.log('This is func1');

}

func1();

function func1(){

console.log('This is last func1');

}

The output result is

This is last func1

This is last func1

Cause analysis: due to the pre parsing mechanism, the declaration of func1 will be promoted, and the code after promotion is

function func1(){

console.log('This is last func1');

}

func1();

func1();

For functions with the same name, the latter will overwrite the former, so This is last func1 is the output result of both times.

(4) , variables, and functions have the same name

alert(foo);

function foo(){}

var foo = 2;

When a variable declaration has the same name as a function, only the function declaration will be promoted, and the variable will be ignored. So the output of the above code is

function foo(){}

Let's show the pre parsed code:

function foo(){};

alert(foo);

foo = 2;

Look at another one

var num = 1;

function num () {

alert( num );

}

num();

The code execution result is:

Uncaught TypeError: num is not a function

According to the normal writing order, for functions and variables with the same name, the variables will overwrite the functions

Code after direct pre parsing:

function num(){

alert(num);

}

var num = 1;

num();

(5) Pre resolution is scoped

The promotion principle is to promote to the variable operation environment (SCOPE).

function showMsg()

{

var msg = 'This is message';

}

alert(msg); // msg undefined

Or write the pre parsed code directly:

function showMsg()

{

var msg;

msg = 'This is message';

}

alert(msg); // msg undefined

(6) . the function expression will not be promoted

func();

var func = function(){

alert("I was promoted");

};

Function is not a function. The reason is that the function expression will not be promoted. It is simply treated as a variable declaration, as follows

var func;

func();

func = function(){

alert("I was promoted");

}

3. Scope

(1) , global scope

The JS code written directly in the script tag is a global scope;

Or in a separate JS file.

The global scope is created when the page is opened and destroyed when the page is closed;

In the global scope, there is a global object window (representing a browser window, which is created by the browser) that can be used directly.

All created variables are saved as properties of the window object.

 

All created functions are saved as methods of window objects.

 

(2) , local scope (function scope):

Inside the function is the local scope. The name of this code only works inside the function

The function scope is created when calling the function. After the function is executed, the function scope is destroyed;

Each time a function is called, a new function scope is created, which are independent of each other.

If all such scopes are listed, there can be a structure: a chain structure pointing outside the function within the function. It is called scope chain.

For example:

function f1() {

function f2() {

}

}

var num = 456;

function f3() {

function f4() {

}

}

(3) , implicit global variables

Declared variables use 'var'. If you do not use 'var', the declared variables are global variables (disabled)

Because this syntax can be used in any code structure, there will be problems in code maintenance. Therefore, do not use it unless for special reasons

Error in the following code

function foo () {

    var i1 = 1 // local

    i2 = 2, // overall situation

    i3 = 3; // overall situation

}

 

 

4. Object

(1) Why should there be an object

function printPerson(name, age, sex....) {
}
// If there are too many parameters of a function, you can use object simplification
function printPerson(person) {
  console.log(person.name);
  ......
}

(2) What is an object

In real life: everything is an object, the object is a specific thing, and a specific thing will have behavior and characteristics.

For example: a car, a mobile phone, a computer, a desk

The car is a kind of thing, and the car parked at the door is the object. Features: red, four wheels, behavior: driving and braking

(3) Objects in JavaScript

The object in JavaScript is actually an abstraction of the object in life.

JavaScript objects are collections of unordered properties.

Its properties can contain basic values, objects, or functions. An object is a set of values that have no order. We can think of objects in JavaScript as key value pairs, where values can be data and functions.

Class="d1"

Key = value

Behavior and characteristics of objects

Features - attributes

Behavior - Method

Tips:

The characteristics of things are represented by attributes in objects.

The behavior of things is represented by methods in objects.

(4) . object creation method

Object Literal

var o = {
  name: 'zs',
  age: 18,
  sex: true,
  sayHi: function () {
    console.log(this.name);
  }
};  

new Object() creates an object

var person = new Object();
  person.name = 'lisi';
  person.age = 35;
  person.job = 'actor';
  person.sayHi = function(){
  console.log('Hello,everyBody');
}

Create objects using factory functions

function createPerson(name, age, job) {
  var person = new Object();
  person.name = name;
  person.age = age;
  person.job = job;
  person.sayHi = function(){
    console.log('Hello,everyBody');
  }
  return person;
}
var p1 = createPerson('Zhang San', 22, 'actor');

Custom constructor

function Person(name,age,job){
  this.name = name;
  this.age = age;
  this.job = job;
  this.sayHi = function(){
    console.log('Hello,everyBody');
  }
}
var p1 = new Person('Zhang San', 22, 'actor');

(5) , properties and methods

1. If a variable belongs to an object, it can be called an attribute of the object. Attributes are generally nouns used to describe the characteristics of things

2. If a function belongs to an object, the function can be called a method of the object. The method is a verb to describe the behavior and function of things

(6) , new keyword

Constructor is a special function. It is mainly used to initialize the object when creating the object, that is, to assign the initial value to the object member variable. It is always used in the statement of creating the object together with the new operator.

1. The constructor is used to create a class of objects, with the first letter capitalized.

2. Constructors are meaningful only when they are used with new.

new does four things when executing:

1. New creates a new empty object in memory

2. New will make this point to the new object

3. New returns the new object

(7) . detailed explanation of this

The direction of this in JS is sometimes elusive. With the in-depth study, we can gradually understand it.

Several features of this function:

1. this is uncertain when a function is defined and can only be determined when it is called

2. General functions are executed directly, and the internal this points to the global window

3. As a method of an object, the function is called by the object, and this points to the object

4. this in the constructor is actually an implicit object, which is similar to an initialization model. All methods and properties are mounted on the implicit object, and then called through the new keyword, so as to realize the instantiation

(8) . use of objects

Traversing the properties of an object

You can traverse an object through the for..in syntax

Delete an object's properties

function fun() { 
  this.name = 'mm';
}
var obj = new fun(); 
console.log(obj.name); // mm 
delete obj.name;
console.log(obj.name); // undefined

  1. JavaScript   error
  1. . JavaScript error

Various errors occur when the JavaScript engine executes JavaScript code. It may be syntax errors, usually coding errors or typos caused by programmers. It may be a spelling error or a missing feature in the language (possibly due to browser differences). Errors may be caused by incorrect output from the server or user. Of course, it may also be due to many other unpredictable factors.

  1. JavaScript, try and catch

try   Statement allows us to define a block of code for error testing at execution time.

catch   Statement allows us to define the code block to be executed when an error occurs in the try code block.

JavaScript statement   try   and   catch   They appear in pairs.
In the following example, we deliberately wrote a typo in the code of the try block. The catch block catches the error in the try block and executes code to handle it.

var txt="";

 function message() {

 try { adddlert("Welcome guest!"); }

catch(err) { txt="There is an error on this page.\n\n";

  txt+="Error Description:" + err.message + "\n\n";

 txt+="Click OK to continue.\n\n";

 alert(txt);

} }
  1. , finally statement

finally statement executes the code block regardless of whether an exception is generated in the previous try and catch.

function myFunction() {

 var message, x;

 message = document.getElementById("p01");

message.innerHTML = "";

x = document.getElementById("demo").value;

 try { if(x == "") throw "The value is empty";

if(isNaN(x)) throw "Value is not a number";

 x = Number(x); if(x > 10) throw "too big"; if(x < 5) throw "Too small"; }

catch(err) { message.innerHTML = "error: " + err + "."; }

 finally { document.getElementById("demo").value = ""; } }
  1. , Throw statement

The throw statement allows us to create custom errors.

The correct technical term is to create or throw an exception.

If throw is used with try and catch, you can control the program flow and generate custom error messages.

Syntax: throw   exception

Exceptions can be JavaScript strings, numbers, logical values, or objects.

This example detects the value of the input variable. If the value is wrong, an exception (error) is thrown. Catch will catch this error and display a customized error message:

function myFunction() { var message, x; message = document.getElementById("message"); message.innerHTML = ""; x = document.getElementById("demo").value; try { if(x == "") throw "The value is empty"; if(isNaN(x)) throw "Not a number"; x = Number(x); if(x < 5) throw "Too small"; if(x > 10) throw "too big"; } catch(err) { message.innerHTML = "error: " + err; } }

Built in object

There are four kinds of objects in javascript: built-in object, browser object, custom object and DOM object. JavaScript provides multiple built-in objects: Math/Array/Number/String/Boolean. Objects are just special data types with properties and methods. To learn how to use a built-in object, just learn how to use its common members (learn by looking up documents). There are many methods for built-in objects. We only need to know the common methods provided by built-in objects and query documents when using them.

(1) How to learn a method?

Test the function of the method, the meaning and type of parameters, the meaning and type of return value, and the demo

2.Math object

The Math object is not a constructor. It has properties and methods of mathematical constants and functions, which are provided as static members.

Math related operations to find members in math (absolute value, rounding).

(1) . common attributes

Math.PI     PI

(2) I. common methods

Math.random()        Generate random number
Math.floor()          Round down

Math.ceil()           Round up
Math.round()         Rounding
Math.abs()           absolute value
Math.max()          Maximum

Math.min()          Minimum value  

Math.sin()           sine

Math.cos()           cosine

Math.pow()          Find exponential power

Math.sqrt()          take a square root

3.Date object

Create a Date instance to process Date and time. The Date object is based on the number of milliseconds from January 1, 1970 (world standard time).

  1. , creation date object

Date() is a constructor

var date = new Date();

  1. . original value of date

getTime(): gets the number of milliseconds since January 1, 1970

valueOf(); Original value, which gets the number of milliseconds since January 1, 1970      

(3) . get the specified part of the date
getMilliseconds()
getSeconds()  // Return 0-59
getMinutes()  // Return 0-59
getHours()    // Return 0-23
getDay()      // Return day of week 0 Sunday   6 weeks 6
getDate()     // Returns the day ordinal of the current month
getMonth()    // Return month, * * * from 0***
getFullYear()  // Returns a 4-digit year   Such as 2016

4.Array object

  1. There are two ways to create array objects

1. Literal mode

2,new Array()

  1. . check whether an object is an array

instanceof      If true is returned, it is an array, and false is a non array

Array.isArray() if it returns true, it is an array, and false is a non array

valueOf()      Returns the array object itself

  1. Stack operation (first in and last out)

Stack: a linear table that performs insert and delete operations at the end of the table. This end is called the top of the stack, and the other end is called the bottom of the stack. Inserting a new element into a stack is also called stack entry, stack entry or stack pressing. It puts the new element above the top element of the stack to make it a new top element; Deleting an element from a stack is also called out of stack or out of stack. It deletes the top element of the stack and makes its adjacent elements become new top elements
push()   Add element
pop()    Delete element

  1. Queue operation (first in first out)

shift()    Delete element
unshift() add element

  1. . sorting method

reverse()    Flip array
sort(sortby); sortby, an optional parameter that specifies the sort order. It must be a function   If no parameters are used when calling this method, the elements in the array will be sorted alphabetically. To be more precise, they will be sorted in the order of character encoding. To achieve this, you should first convert the elements of the array into strings (if necessary) for comparison.

  1. . operation method

concat()     Splice parameters into the current array   Or to join two or more arrays
slice(start,end)      1. Intercept elements from start to end, including start and excluding end, and return a new array. Start and end are indexes,

2. The original array will not be changed

splice()     1. Intercept elements from start, intercept length, and return a new array. Start is the index and length is the number

However, the contents intercepted from the original array will be deleted

  1. Location and method

indexOf()         The index value is returned when the location is found. If it is not found, it returns - 1. The location appears for the first time

lastIndexOf()   If - 1 is not found, the location of the last occurrence of the element

The above methods are only different in search order, and the results are all index values

  1. Array iteration method

Iteration (i.e. constant substitution)

1. The forEach() method is used to call each element of the array and pass the element to the callback function

array.forEach(function(currentValue, index))

currentValue  Required. Current element

Index   Optional. Current element index value

You can get the value in each array without returning a value

Question Thinking: will the iterative method change the original value?

2. The every() some () method is used to detect whether all elements of the array meet the specified conditions (provided by the function).

The parameter of some(), every() method is a callback function. The first parameter in the callback function is the element of the array, and the second parameter is the index of the array

  some(), every() method will return a new array

Formula: var flag1 = arr3.every(function (value, index) {

     return value > 55;

})

   console.log(flag1);

 var flag2 = arr3.some(function (value, index) {

    return value >= 88;

  })

  console.log(flag2)

every(): judge whether all expressions in the callback function are satisfied. If so, the return value is true, and if one is not satisfied, it is false

some determines whether one of the expressions in the callback function is satisfied. If at least one is satisfied, the return value is true

3. filter() and map()

filter() filters elements according to specified conditions and returns a new array;

map() returns a new array based on mathematical operations

//filter(): filter elements according to specified conditions and return a new array

  var new1 = arr.filter(function (value, index) {

    return value >= 33;

  })

  console.log(new1);

  //map(): returns a new array according to the mathematical operation

  var new2 = arr.map(function (value, index) {

    return Math.pow(value, 2);

  })

  1. . empty the array

Mode 1 recommendation
arr = []
Mode 2
arr.length = 0
Mode 3
arr.splice(0, arr.length)

  1. Array conversion string

The join() array is converted to a string and divided by parameters

5. Basic package type

To facilitate the operation of basic data types, JavaScript also provides three special reference types: String/Number/Boolean

// What is the problem with the following code?
// s1 is the basic type, which has no method to operate
var s1 = 'zhangsan';
var s2 = s1.substring(5);
​
// When calling s1.substring(5), first wrap S1 into a temporary object of String type, then call the substring method, and finally destroy the temporary object, which is equivalent to:
var s1 = new String('zhangsan');
var s2 = s1.substring(5);
s1 = null;


// Create an object of the basic wrapper type
var num = 18;               //Value, basic type
var num = Number('18');     //Type conversion
var num = new Number(18);   //Basic wrapper type, object
// The Number and Boolean basic packing types are basically not used, which may cause ambiguity. For example:
var b1 = new Boolean(false);
var b2 = b1 && true;        // What is the result

6.String object

(1) . immutability of string

var str = 'abc';
str = 'hello';
// When str is re assigned, the constant 'abc' will not be modified and is still in memory
// Re assigning a value to a string will re open up space in memory, which is characterized by the immutability of the string
// Due to the immutability of strings, there will be efficiency problems when a large number of strings are spliced

(2) , create string object

var str = new String('Hello World');
// Gets the number of characters in the string
console.log(str.length);

(3) Common methods of string objects

All methods of string will not modify the string itself (the string is immutable), and a new string will be returned after the operation is completed

1 character method
charAt()        // Gets the character at the specified position
charCodeAt()    // Gets the ASCII code of the character at the specified position
str[0]          // HTML5, IE8 + support and charAt() equivalent
2 string operation method
concat()        // Splice string, equivalent to +, + is more commonly used
slice(start,end)         // Start from the start position and intercept to the end position, but end cannot
substring(start,end)     // Start from the start position and intercept to the end position, but end cannot
substr(start,length)         Intercept length characters from the start position
indexOf()       // Returns the position of the specified content in the meta string. If not, returns - 1; (from front to back, it ends when the first one is retrieved)
lastIndexOf()   // Returns the position of the specified content in the meta string. If not, returns - 1; (from back to front, the first one is retrieved)
trim()          // Only whitespace before and after the string can be removed
Case conversion method
toUpperCase()   // Convert to uppercase
toLowerCase()   // Convert lowercase
The search() / / method is used to retrieve the substring specified in the string and return the starting position of the substring
replace(old,new) / / replace string replace string new replace old
split() / / split string returns an array.. The elements of an array are divided by parameters

Tags: regex Network Protocol TCP/IP

Posted on Thu, 18 Nov 2021 08:51:40 -0500 by bolter