The functions and effects of javascript, the basic functions of javascript are

Hello everyone, this article will focus on the functions and effects of javascript. The basic functions of javascript are something that many people want to understand. To understand the javascript definitive guide, you need to understand the following things first.

Article directory
    • 1. The complete composition of JavaScript*
      • ECMAScript [js standard]
      • DOM document object model [document object model]
      • BOM browser object model [Browser Object Model]
    • 2. Characteristics of JavaScript
    • 3. The role of JavaScript
    • 4. The location of JavaScript
      • 4.1 Internal styles
      • 4.3 External styles
    • 5. Comments in JavaScript
    • 6. Variables and data types in Java
      • 6.1 Variables
        • Keywords and reserved words
        • Variable command rules
        • Use of variables
        • Characteristics of variables in js
      • 6.2 Data types
        • 6.2.1 Basic data types
          • String
          • NumberNumber
          • Boolean type boolean
          • Null
          • UndefinedUndefined
        • 6.2.2 Introduction to reference data types
          • ObjectObject
          • ArrayArray
          • Function
        • How basic data types and reference data types are stored in memory

1. The complete composition of JavaScript*

  • ECMAScript, describes the syntax and basic objects of the language.
  • Document Object Model (DOM), which describes the methods and interfaces for processing web content, was rewritten by GPT.
  • Browser Object Model (BOM), describes the methods and interfaces for interacting with the browser.
ECMAScript [js standard]

A standard composed of single-line comments and block comments ( // , /**/), variables, operators, flow control statements, arrays, objects, functions, regular expressions, etc. Currently, basically all js interpreters are compatible with ECMAScript.

DOM document object model [document object model]

Simply put it is an API that uses JavaScript to operate html. It is an application programming interface for XML but extended for HTML. DOM maps the entire page into a multi-node structure.
For example:
var dom=document.getElementsByTagName(“input”);
var dom=document.getElementById(“input_name”);
dom.οnclick=function(){}

BOM browser object model [Browser Object Model]

To put it simply, JavaScript is used to operate the browser’s API. Developers can use BOM to control parts other than the page displayed by the browser.
For example:
Pops up a new browser window; functions to move, zoom, and close the browser; navigator object that provides detailed information about the browser; location object that provides detailed information about the page loaded by the browser; screen object that provides detailed information about the resolution of the user’s monitor; Support for cookies; support for XMLHttpRequest, ActiveXObject custom objects in IE
like:
alert()/prompt()/confirm()
setInterval()/setTimeout()
XMLHttpRequest,Ajax

It should be noted that only ECMAScript is the standard, which means that it runs the same in most browsers and js parsers (node). However, DOM and BOM are APIs provided by major browser manufacturers, and they are similar in use. However, there may also be some incompatibilities

2. Characteristics of JavaScript

1. Script language for sequential interpretation and execution
Its basic structural form is very similar to c, c++, and java. But it does not need to be compiled first like these languages, but == is interpreted line by line during the running of the program. ==It needs to be embedded into the html page and let the browser interpret and execute it.
2. Object-based language
Java is an object-based language, and objects can be created in the program
3. Simplicity
It is a simple and compact design based on java’s basic syntax statements and control flow. The syntax in basic java can be used.
into java, so if you have learned the java language, learning java is relatively simple.
4. Weakly typed language
Its syntax is loose and the requirements are not strict. For example, a variable can be used directly without declaring it before, you don’t need to declare the variable type when declaring a variable, etc.
5. Event driven
Operations on the page, such as left/right clicks and double-clicks, monitoring of keys on the keyboard, mouse movement, mouse dragging, mouse scrolling, etc., can be handled by JavaScript.
6. Dynamic
JavaScript can respond directly to user or customer input without going through the web service program.
7. Security
JavaScript does not allow access to the local hard disk, cannot store data on the server, and does not allow modification and modification of network documents.
Deletion, information browsing or dynamic interaction can only be achieved through the browser. Thus effectively preventing data loss
8. Cross-platformability
JavaScript depends on the browser itself and has nothing to do with the operating environment. As long as the computer can run the browser and supports java
browser will execute correctly. However, different browsers and different versions of the same browser support JavaScript differently.
(Browser compatibility)

3. The role of JavaScript

1. Dynamically improve the design layout of the web page (operate the label elements in the page)
2. Verification form
3. Detect browsers and control browser behavior
4. Create cookies
5. Handle events triggered on the page
6. JavaScript should also be used when using ajax

4. Location of JavaScript

4.1 Internal Style

The content in js is written between < > tags, and the tags are placed in the < body > or < head > tag, for example:
1. Written in the head tag

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>first</title>
    <!-- JavaScript is written in the head tag -->
    < type="text/java">
        document.write("hello world");
    </>
</head>
<body>
    
</body>
</html>

2. Write it in the body tag

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>second</title>
</head>
<body>
    <!-- JavaScript is written in the body -->
    < type="text/java">
        document.write("hello world");
    </>
</body>
</html>

Replenish:
The difference between using JavaScript in the body and in the head
The JavaScript in the body section will be executed when the page loads, and the JavaScript in the head section will be executed when called.
Because the browser parses html from top to bottom. If JavaScript is placed in the head, it will be parsed first, but the body has not been parsed at this time, so it will return a null value. Generally, a listener is bound and the code is executed after all the HTML documents have been parsed, for example: windows.onload = function(){//Put the executed code here}, this means that if we want to define a global object, and this object is a button on the page, we must put it in the body. The reason is obvious: if we put it in the head, then when you define , that button has not been loaded, and it may get an undefind value, so it is generally customary to put JavaScript at the end of the body.

3. Write it in the event attribute of the label element

<div onclick="java:alert('hello world')"></div>
4.3 External styles

Similar to the reference of css style sheet (written in an external js file, refer to the external js file in HTMl)

HTML file

< type="text/java" src="test.js"></>

test.js file

 document.write("hello world");

5. Comments in JavaScript

Similar to most languages, JavaScript also requires comments to explain the meaning of its code or for code debugging. The commented code will be ignored by the browser and will not be executed.
(1) Single line comment:

//Comment content

(2) Block comments (multi-line comments)

/*
Annotation content
*/

6. Variables and data types in Java

6.1 Variables

A variable is a container of value that can change at any time. ECMAScript variables are weakly typed (loosely typed) and can be used to store any type of data.
The var keyword is used to define variables, which means that any type of variable can be declared using the var keyword.

Keywords and reserved words

Keywords: words with special functions in js. Common ones currently include break, do, try, typeof, case, if, else, etc. . .
Reserved words: words that may become keywords in the future, such as: package, abstract, etc. Because they are constantly changing, I will not list them one by one.

Command rules for variables

1. Case sensitive
For example: typeof is a keyword, typeOf is different from typeof, it is not a keyword
2. Identifier rules
An identifier refers to the name of a variable, function, attribute or parameter of a function. It is one or more characters combined according to the following rules:
1. Composed of letters, numbers, underscores, and $
2. Can only start with letters, underscores, and $
3. Keywords cannot be used as identifiers
4. Naming uses camel case naming (that is, when the identifier consists of multiple words, the first letter of the first word is lowercase, and the first letters of subsequent words are all capitalized), for example: numberOfPeople

Use of variables

(1) Declare variables

var variable name;

(2) Variable initialization

Variable name = variable value;

(3) Initialize variables while declaring

var variable name = variable value;

(4) Declare multiple variables (separated by commas)

var variable name 1 = variable value 1, variable name 2 = variable value 2;
Characteristics of variables in js

1. The usual use of variables in js is divided into the following three steps:

//Variable declaration
var a;
//Variable initialization
a = 3;
//Variable call
console.log(a);

2. Since js is a weakly typed language, it has the characteristics of weakly typed language variables:

  1. The data type of the variable is determined during initialization
  2. The data type of a variable can change at any time
  3. Type breakdown is not obvious

3. Variables can be declared repeatedly:
Look at the following case:

var a = 3; //a here is an integer type
var a = "hello world"; //a here is a string type

4. Variable value update

var b = 20;
b = "js";

5. Variable declaration improvement
For example:

console.log(a); //undefined
var a = 3;

Equivalent to the following

var a;
console.log(a); //undefined
a = 3;

Before all code is executed, the js interpreter will promote all variables declared by var in js. You can see that the original var a = 3 is split into two parts, the var a declaration part and the a = 3 variable initialization part, and the declaration part is brought to the front. This is “declaration promotion”, and because the declaration is advanced , the assignment statement is after the console statement, so the output is undefined

6. Scope of variables declared by var
Analyzing the following examples and comments can help understand:
Additionally, function declarations will also be made in advance, and function declarations will be in front of variable declarations. Please see this article for details:Function
(1) Example 1: The variable declaration of var will only be promoted to the front of the current scope in advance.

//This is a function named foo
function foo(){
  if(true){
    var a = 3; //local variable
    console.log("inner",a);//inner 3
  }
  console.log("outer",a);//outer 3
}
foo();
console.log(a);//error!

analyze:
(1) Separate the declaration and initialization of the a variable in the if statement in the function foo, and advance the declaration of the a variable to the front of the function. What is left in the if statement is the initialization of the variable, and the assignment is 3, because the declaration is advanced. , the scope is within the current function, that is, between the brackets of function foo, so the statement console.log("outer",a) outside the if statement is also within the declaration scope of the a variable within, and a=3 is initialized in the if statement, so the value of variable a in console.log("outer",a); outside the if statement is also 3.
(2) console.log(a); outside function foo is not within the scope of local variable a, and the variable is not declared and initialized within its own scope, so it will Report an error.

The above code is equivalent to:

function foo(){
  var a; //Declare local variables
  if(true){
    a = 3; //Assign a value to the variable
    console.log("inner",a);//inner 3
  }
  console.log("outer",a);//outer 3
}
foo();
//console.log(a);//error!

(2) Example 2: If a variable is defined in a function without adding var, the variable is a global variable.

function test(){
  message = "hello";
}
test(); //After calling the method, message is assigned the value hello
console.log(message); //hello

Equivalent to:

var message;
function test(){
  message = "hello";
}
test(); //After calling the method, message is assigned the value hello
console.log(message); //hello

(3) Example 3: A variable defined with the var operator will become a local variable in the scope in which the variable is defined.

function b() {
  a = 10;
  return;
}
var a = 1;
b(); //b function call
console.log(a);//10

analyze:
Similarly, a is a global variable. When calling function b, a is assigned a value. According to the rule that variables can be assigned repeatedly, the value originally stored in a is replaced during the calling of function b, so the output result is is the value 10 of the variable in function b.

(4) Example 4: The this keyword can call global variables

x = 1;//window.x global.x This is the global object, also equivalent to the global variable var a = 1;
console.log(x); //1
function y() {
  console.log(x); //undefined
  console.log(this.x);//1, you need to call the global object through the this keyword
  var x = 2;
  console.log(x); //2 Reassign x = 2 through local variables;
}
y();
console.log(x); //1

analyze:
(1) The outermost x=1 is a global variable and can be used globally
(2) For the first output statement in the y function, var x = 2; in the function is a local variable, and it is actually split into two parts: declaration and assignment, and the declaration is promoted to the front of the function scope. At this time, the local variables have not been assigned, so the first output statement is undefined.
(3) The second output statement in the y function can be called to the global object through the this keyword, so the output is 0
(4) The third output statement in the y function previously defined the local variable x and assigned a value, so the output is 2, but the assignment only takes effect within the scope of the y function.
(5) The last output statement is not affected by the local variable assignment in the y function, so the output value is the value of the global variable x

(5) Example 5

//Function scope: local scope
var a = 1; //global variable
function b() {
  a = 10; //local variable
  return;
  //a function declaration, advance variable a, consider a to be a variable in the scope of function b, with local effects
  function a(){}
}
b();
console.log(a); // 1
6.2 Data types

Common data types in JavaScript
Basic types: String, Number, Boolean, Null, Undefined, and Symbol. .
Reference types: Object, Array, Function

Supplement: Symbol is a new primitive data type introduced in ES6, which represents unique values.

Strings in Java are reference types, don’t get confused

Dynamic typing in Java means that the same variable can be used as different types, as follows:

var x; // x is undefined
var x = 5; // now x is a number
var x = "John"; // now x is a string
6.2.1 Basic data types
String

Strings are variables that store characters (such as “Bill Gates”). A string can be any text within quotes, which can be single or double quotes. as follows:

var carname='Volvo XC60';
var carname="Volvo XC60";

Added: You can use quotes within a string, as long as they don’t match the quotes surrounding the string.
You can use character literals to escape characters, as follows:
\
Line feed \t Tab \b Backspace
\r carriage return \ slash ’ single quote
” Double quotes

The character length can be obtained through the length attribute, as follows:

var str = "I am a string";
console.log(str);
console.log(str.length);
var s4='\
\t\b\r';

Built-in functions in strings

var s = "hello world";

//Get the length of the string
console.log(s.length);

// Starting from the position with subscript 3, intercept 4 characters, including the character at the position with subscript 3
console.log(s.substr(3,4));

//Start from the position with subscript 6 and intercept to the position with subscript 8, but do not include the character with subscript 8 [6,8)
console.log(s.substring(6,8));

//trim() removes spaces on both sides of the string, but this method may not be supported by the browser.
console.log(s.trim().length);

//Convert string to uppercase
console.log(s.toUpperCase());

//Convert string to lowercase
console.log(s.toLowerCase());

//Split the string and return an array
console.log(s.split(" "));
console.log(s.split(" ").length);
console.log(s.split(" ")[0]);
console.log(s.split(" ")[1]);
Number

JavaScript has only one number type, and all numbers agree to be represented by Number, that is to say, whether you are an integer (int), a floating point number (single precision float, double precision floating point double), or a binary (Binary), Octal (Octal), decimal (decimal system), and hexadecimal (Hexadecimal) are all represented by Number.

var num1 = 34; //Write without decimal point
var num2 = 010; //8
var num3 = 0x10; //16
console.log(num1,num2,num3);

var f1 = 3.1415926; //3.1415926
var f2 = 3.125e7; //31250000 //Scientific notation
console.log(f1, f2);

Numerical detection
Why do we need numerical testing?
For example: var result = 10 / 'a'; The result cannot be calculated. For another example, if the result of a number exceeds the numerical value range of JavaScript, it cannot be expressed either. .

What is Nav?
In JavaScript, if an operand that is supposed to return a numerical value does not return data, the result is represented by NaN;

Method to determine whether the returned result is non-numeric:
isNaN(variable); //If it is not a numerical value, the return value is true, otherwise it is false

Value range:
Due to memory limitations, ECMAScript cannot save all the values in the world.
The smallest value that ECMAScript can represent is stored in Number.MIN_VALUE.
The largest value that can be represented is stored in Number.MAX_VALUE.
If the result of a certain calculation exceeds the JavaScript numerical range, Infinity (positive infinity) or -Infinity (negative infinity) will be returned.

Value range detection
Use the isFinite() function to determine whether the parameter is between the maximum value and the minimum value. If so, return true

Boolean type boolean

Boolean (logic) can only have two values: true or false, corresponding to the numbers 1 and 0

Empty Null

There is only one value of this type, which is null. null can represent a pointer to a null object.

How to use: If a variable is going to save an object in the future, you can initialize the variable to null instead of anything else. In this way, you can know whether the corresponding variable has saved a reference to an object by checking the null value.

Undefined

Undefined This type indicates that the variable does not contain a value, is undefined, and has not been initialized and assigned a value.
like:

var a;
console.log(a,typeof a);//undefined 'undefined'
//typeof is used to determine the data type of a

The relationship and difference between undefined and null
undefined inherits null, so the result of undefined == null is true, but null means an empty object, and undefined means undefined;
Null has different uses than undefined. Null can be used to represent an empty object, but there is no need to explicitly set the value of a variable to undefined.

====================================
Generally, basic types themselves do not have any methods, but why can the three basic data types of Boolean, String, and Number be able to call methods? This is related to their corresponding basic packaging types. For details, please see this introduction to basic packaging types.

6.2.2 Introduction to reference data types

In addition to the above basic data types in js, all other types can be attributed to reference data types. Here is a brief introduction

Object Object

Objects are objects that simulate real life. Objects are composed of key-value pairs. All key-value pairs are enclosed by curly braces.
The types of objects that already exist in javaScript are:

var v = new Date();
var obj1 = new Object();//Object object
var obj2 = {};

var arr1 = new Array();//Array object
var arr2 = [];

var boo1 = new Boolean(true), boo2 = true;//Boolean object
var num1 = new Number(123), num2 = 123.45;//Number object
var str1 = new String("abc"), str2 = 'abc';//String object 12345678910

Custom objects:
Format:

var object name = {
Attribute 1: Attribute value 1,
Attribute 2: attribute value 2
}

For example:

var dog = {
name: 'momo',
age: 4
}

Get the attributes of the object: Format: Object name.Attribute name

Please see here for object details

Array Array

An array is a special object that contains multiple values. Values are separated by commas, and all values are enclosed in square brackets.

var classArr = ['web2104','web2105','web2106']
var studentArr = ['zhangsan','lisi','wangwu']

Corresponding data can be obtained through array subscripts

classArr[0]; // web2104

For a detailed introduction to arrays, please see here

Function

Functions are code execution units used to implement certain special functions.

function sum(a, b) {
  return a + b;
}
//Execute function
sum(1,2); // 3

Please see here for function details

How basic data types and reference data types are stored in memory

For basic types:
Variables and values of basic types are stored in the stack area.
For example:

//b directly stores the value of a, so the values of variables a and b are the same
var a = 123;
b = a;

The memory is as shown in the figure:

When the value of b is changed to 456, the value in a will not be changed at the same time. That is to say, the value of the basic data type is stored in the stack, and the value exists independently. Modifying a value will not affect Other variables

For reference types:
The value stored in a reference type is the address of an object, and this object is stored in the heap area of memory when it is created. Find the corresponding object in the heap area through the address stored in the stack area.

//Define an object obj1
var obj1 = {
  name: 'zhangsan'
}
//Define an object obj2 and assign object obj1 to object obj2
var obj2 = obj1;
//The output results of both objects are the same
console.log(obj1.name); //zhangsan
console.log(obj2.name); //zhangsan

// If you modify the name of obj1 at this time
// When the obj1 attribute name changes to "lisi", the obj2 attribute name also changes to "lisi"
obj1.name = 'lisi';
console.log(obj1.name); //lisi
console.log(obj2.name); //lisi

The memory diagram is as follows:

Analysis: Objects ojb1 and obj2 store the real values in the heap memory, and the values stored in the stack memory are the addresses corresponding to the real values.

Supplement: Deep copy and shallow copy
Mainly for reference data type parameters, shallow copy means copying only the reference address, and deep copy means cloning the object.

How to implement deep copy

  • Implement deep copy through json object (JSON.stringify, JSON.parse)
  • Object.assign()copy
  • Lodash function library implements deep copy
  • Implement deep copy recursively