JavaScript Basics

Posted by wilburforce on Wed, 23 Feb 2022 13:21:14 +0100

First acquaintance with JavaScript

Refer to the video of wisdom podcast.

definition

javascript is a scripting language that runs on the client side (similar to css)

effect

  • Form dynamic inspection
  • Web effects
  • Server development (Node.js)
  • Desktop program (Electron)
  • APP(Cordova)
  • Control hardware - Internet of things (Ruff)
  • Game development (cocos2d JS)

js composition

1.javascript syntax (ECMAScript)
2. Document oriented object model (DOM)
3. Browser object model (BOM)

JavaScript variables

definition

A piece of ## space requested by a program in memory to hold data

use

1. Declare variables 2 assignment

// Declaration keyword var
var  age; // Declare a variable named age
// assignment
age=10; // Assign a value to this variable
// Initialization of variables
var age = 18; // Recommended writing method

case

Use of variables: 1 A dialog box pops up, prompting the user to enter the name
2. A dialog box pops up to output the name just entered by the user

	var myname = prompt('Please enter your name');
    alert(myname);

Output result:

Variable syntax extension

  1. Update variable
var age = 18;
age = 20; // The second value will completely overwrite the first one
  1. Declare multiple variables
var age=18,address='Huoying Village'; // Multiple variables are separated by commas
  1. exceptional case
var sex; // Only declare that the result without assignment is undefined
console.log(tel); If you do not declare or assign a value, you will report an error if you directly use a variable
qq = 110; // Use of direct assignment without declaration 

Naming rules for variables

case

Exchange the values of two variables

	var temp; // Temporary variable
    var apple1='green apple';
    var apple2 = 'Red apple';
    temp = apple1;
    apple1 = apple2;
    apple2 = temp;
    console.log(apple1);
    console.log(apple2);

Summary

JavaScript data type

Introduction to data types

// The variable data type of js is determined according to the value on the right of the equal sign only when the program is running
var num = 10; // Numerical type
var str = 'pink' // String type
// js dynamic language, the data type of variables can be changed

Simple data type

Digital Number

var num = 10;
var PI = 3.14;
// 1. Octal 0-7 in our program, the number preceded by 0 indicates octal
var num1 = 010; // 010 octal to hexadecimal is 8
// 2. Hexadecimal 0-9 a-f adds 0x before the program number to indicate hexadecimal
var num2= 0xa; // 10
// 3. Maximum value of digital type (understand)
alert(Number.MAX_VALUE);
alert(Number.MIN_VALUE);
// Three special words (understanding)
alert(Infinity) // Infinity
alert(-Infinity) // Infinitesimal
alert(NaN) // Non numeric

isNaN() this method is used to determine non numeric values

String type string

It can be single quotation mark or double quotation mark. It is recommended to use single quotation mark in js

nesting

Pithy formula: outer double inner single, inner double outer single

var str = 'I am a"tall, rich and handsome"Programmers';

String escape character

Escape characterinterpretative statement
\ nnewline
\ \Slash\
\ 'Single quote '
\"Double quotation mark“
\ttab indent
\bSpace

String length

Gets the length of the string. The available length property

var str = 'my name is andy';
console.log(str.length) // 15

String splicing+

Splicing method: String + any type = string after splicing
+Number formula: numerical values are added and characters are connected
Splicing reinforcement: splicing strings and variables

var age =18;
console.log('pink teacher'+ age +'year') // Mr. pink is 18 years old
// Pithy formula: introduction and addition
case

Show age simple js interaction
1. Pop up an input box (prompt) for the user to enter the age
2. Save the input value with variables and splice the characters
3. Use the alert statement to pop up the alert box

Boolean

There are two values: true and false

var flag = true;
var flag1 = false;
console.log(flag + 1); // 2
console.log(flag1 + 1); // 1

undefined Null and empty data

If the variable declaration is not assigned, it is the undefined data type
Null is an empty data type

console.log(undefined + 'pink');//  undefinedpink 
console.log(undefined + 1); // NaN
console.log(null + 'pink'); // nullpink
console.log(null + 1); // 1

Gets the data type of the variable

The typeof property is available

var num = 10;
console.log(typeof num); // Number
var str = 'pink'; 
console.log(typeof str); // String
var flag = true; 
console.log(typeof flag);// Boolean
var vari = undefined 
console.log(typeof vari);// undefined
var timer = null; 
console.log(typeof timer); // object

Literal
Is the representation of a fixed value in the source code

Data type conversion

Convert to string type

The plus sign splicing string is the focus

// Implicit conversion
var num = 10;
console.log(num + '');

Convert to digital (key)

Remember the first two

var age = prompt('Please enter your age');
// ParseInt (variable) results in an integer
console.log(parseInt(age));
console.log(parseInt('3.94')); // 3 rounding
console.log(parseInt('120px')); // 120 will remove px units
console.log(parseInt('rem120px')); // NaN
// The result of parsefloat (variable) is a decimal floating point number

case

1. Calculate age

2. Simple adder

Convert to Boolean

Values representing null and negative will be converted to false, such as' ', 0, NaN, null and undefined
All other values are true

Operation case

		var uname = prompt('Please enter your name');
        var age = prompt('Please enter your age');
        var sex = prompt('Please enter your gender');
        var ages = prompt('How old are you now');
        var page = parseInt(ages) + 5;
        console.log(typeof page);
        console.log('Your name is:' + uname);
        console.log('What is your age:' + age);
        console.log('What is your gender'+ sex);
        console.log('By my estimate,Five years later,You may' + page +'Yes');

operator

It is a symbol used to realize the functions of assignment, comparison and arithmetic operation

Arithmetic operator

// Residual%
console.log(5 % 3); // 2
console.log(3 % 5); // 3
//  There will be problems in floating-point arithmetic
console.log(0.1 + 0.2); 
console.log(0.07 * 100);

Floating point precision
Expressions and return values
An expression is a formula composed of numbers, operators, variables, etc

console.log(1 + 1); // 2 is the return value
// Calculate the expression on the right and return the value to the left

Increment and decrement operators

Must be used with variables

Pre increment operator

Pithy formula: first add 1, and then return the value

// If you want a variable, add 1 yourself 
var num = 1;
++num; // Similar to num = num + 1
var p = 10;
console.log(++p + 10); // 21
++p p The two values change together

Post increment operator

Pithy formula: return the value first, and then add it by yourself

var num = 10;
num++; // Similar to num = num + 1
var p = 10;
console.log(p++ + 10); // 20
console.log(p); // 11

Summary

Most use post increment or decrement, such as num++,num –

Comparison operator

Returns a Boolean value

=Summary

Logical operator

The return value is also a Boolean value, which is often used for multiple condition judgment in later development

Logic and: the result is true only if both sides are true
Logical or: the result is false only if both sides are false
Logical non: negative

Short circuit operation (logic interrupt)

Principle: when there are multiple expressions (values) and the expression value on the left can determine the result, the value of the expression on the right will not be calculated

  1. Logic and: expression 1 & & expression 2
  2. If the result of expression 1 is true, expression 2 is returned
  3. If expression 1 is false, expression 1 is returned
console.log(123 && 456); // 456
console.log(0 && 1 + 2 && 456 * 789); // 0
// If the empty or negative ones are false, the rest are true, such as: 0 '' null undefined NaN
  1. Logical or: expression 1 | expression 2
  2. If the result of expression 1 is true, expression 1 is returned
  3. If expression 1 is false, expression 2 is returned
var num = 0;
console.log(123 || num++); // 123
console.log(num); // 0

Logical interrupts are important and affect the value of the output code

Assignment Operators

Concept: an operator used to assign data to a variable

var num = 10;
num += 2; // Similar to num = num + 2;
console.log(num); // 12

Operator priority


The logical non priority in unary operators is the highest
Logical and have higher priority than logical or

JavaScript process control

Process control mainly includes sequence structure, branch structure and cycle structure

Sequential structure

The program will be executed in the order of the code

Branching structure

According to different conditions, execute different path codes to get different results

if statement

// Syntax structure of if
if(Conditional expression) {// Execute statement}
// Execution idea: if the expression in if is true, the execution statement in braces will be executed 

Execution process
case

// Case of entering Internet cafe
var age = prompt('Please enter your age');
if(age >= 18) {
	alert('Go online');
}

ifelse double branch statement
Finally, only one statement can be executed, one out of two

if (Conditional expression) {
 // Execute statement 1
} else {
	// Execute statement 2
}
// If the expression result is true, execute statement 1; Otherwise, execute statement 2

Execution process

if else if statement (multi branch statement)

// Select one more process else if how many are written according to the actual needs
if (Conditional expression 1) {
	// Statement 1
} else if (Conditional expression 2) {
	// Statement 2
}  else if (Conditional expression 3) {
	// Statement 3
} 
else {
 // If none of the above conditions is true, execute this code
}

Execution process

Ternary expression

A formula consisting of ternary operators

// If the conditional expression is true, the value of expression 1 is returned
 Conditional expression ? Expression 1 : Expression 2 // grammatical norm

var num = 10;
var result = num > 5 ? 'yes' : 'no, it isn't';
console.log(result); // yes

case
Digital complement 0

var time = prompt('Please enter a 0-59 A number between');
var result = time < 10 ? '0' + time : time;
alert(result);

switch Statements

When setting a series of specific value options for variables, you can use switch

// Write according to the actual needs, and match the value of the expression with the option value after the case
switch (expression) {
	case value1:
		// Execute statement 1;
		break;
	case value2:
		// Execute statement 2;
		break;
	default:
		// Execute the last statement;
}

matters needing attention

var num = 3;
switch(num) {
	case 1:
		console.log(1)
		break;
	case 3:
		console.log(3)
		break;
}
// Expressions are often written as variables
// When the value of num matches the value in case, it is congruent
// Remember to write break

Difference between switch statement and if else statement

Cyclic structure

The purpose of the loop: some statements can be executed repeatedly

for loop

// for repeatedly executes some code, which is usually related to counting
for(initialize variable;Conditional expression;Operation expression) {
	// Circulatory body
}
// example
for(var i = 1; i <= 100;i++) {
	console.log('Hello!');
}
// Execution process
// 1. The sentence var I = 1 is executed only once
// 2. Execute the loop body if the conditions are met
// i. end of the first round of execution
// 4. Judge whether the conditions are met again, and exit the cycle until the conditions are not met

Breakpoint test

// The for loop can execute the same code
var num = prompt('Please enter the number of times');
for(var i = 1; i <= num;i++) {
	console.log('I was wrong')
}
// The for loop can execute different code because of the existence of counter variable i
for(var i = 1; i <= 100; i++) {
	console.log('This man this year' + i + 'Years old');
}
// The for loop repeats some of the same operations

Double for loop

for(Initialization variable of outer layer;Conditional expression of outer layer;Operation expression of outer layer){ 
	for(Initialization variable of inner layer;Conditional expression of inner layer;Operation expression of inner layer)
	 {
	 // Execute statements;
	}
}
// The inner loop can be regarded as the statement of the outer loop
// The outer layer circulates once, and the inner layer circulates all
 for (var i = 1; i <= 3;i++) {
            console.log('This is the second phase of the outer cycle' + i  + 'second');
            for (var j = 1; j <=3;j++) {
                console.log('This is the second stage of the inner circle' + j  + 'second');
            }
        }

Summary

while Loop

while (Conditional expression) {
	// Circulatory body
}
// When the conditional expression is true, the loop body is executed, otherwise exit the loop
var num = 1;
while (num <= 100) {
	console.log('How are you');
	num++;
}
// There are also counter initialization variables
// There is also an operation expression to complete the update of the counter and prevent dead circulation

do while loop

do {
	// Circulatory body
} while (Conditional expression)
// Execute the loop body once before judging the condition
// If the conditional expression is true, the loop body will be executed, otherwise exit the loop
var i = 1;
do {
	console.log('How are you');
	i++;
} while (i <= 100)

Cycle summary

continue keyword

Used to immediately jump out of this cycle and continue to the next cycle

// Exit this cycle and continue with the rest
for (var i = 1; i <= 5;i++) {
	if (i == 3) {
		continue;
	}
	console.log('I'm eating the third' + i + 'A steamed stuffed bun')
}

break keyword

Used to jump out of the entire loop immediately

for (var i = 1; i <= 5;i++) {
	if (i == 3) {
		break;
	}
	console.log('I'm eating the third' + i + 'A steamed stuffed bun')
}

JavaScript array

Definition: an elegant way to store a set of data under a single variable name
How arrays are created

// 1. Create an array with new
var arr = new Array(); // Create an empty array
// 2. Use array literal to create an array
var arr = []; // Recommended way
var arr1 = [1, 2, 'pink', true]; // Can store any data type

Accessing array elements

Index: the ordinal number used to access array elements (array subscript starts from 0)

var arr1 = [1, 2, 'pink', true];
console.log(arr1[2]); // pink
console.log(arr1[3]); // true
// If there are no array elements, the output result is undefined

Traversal array

Access the elements of the array from beginning to end once

var arr = ['red', 'green', 'blue'];
for (var i = 0; i < 3; i++) {
	console.log(arr[i]);
}

Array length

Dynamically detect the number of array elements

// Syntax: array name length
// improvement
var arr = ['red', 'green', 'blue'];
for (var i = 0; i < arr.length; i++) {
	console.log(arr[i]);
}

case

1. Calculate the sum of the array and 2 average value

 		var arr = [2, 6, 1, 7, 4];
        var sum = 0;
        var average = 0;
        for (var i = 0; i < arr.length; i++) {
            sum += arr[i]; // We are adding elements in the array, not i
        }
        average = sum / arr.length;
        console.log(sum,average);

3. Maximum value of array

	   var arr = [2, 6, 1, 77, 52, 25, 7];
       var max = arr[0];
       for (var i = 0; i < arr.length;i++) {
           if (arr[i] > max) {
               max = arr[i];
           }
       }
       console.log(max);

4. Convert array to split string

var arr = ['red', 'green' ,'blue', 'pink'];
       var str = '';
       var sep = '!';
       for (var i = 0; i < arr.length; i++) {
           str += arr[i] + sep;
       }
       console.log(str);

New element in array

// 1. By modifying the length
var arr = ['red', 'green', 'blue'];
console.log(arr.length); // 3
arr.length = 5;
// 2. Modify the index number and append the array element
var arr1 = ['red', 'green', 'blue'];
arr1[3] = 'pink';
console.log(arr1); // 4
arr1[0] = 'yellow'; // Replace the original array element

case

Create a new array

It stores 10 integers (1-10)

 var arr = [];
       for (var i = 0; i < 10; i++) {
        //    arr = i;  Remember not to assign values to arrays directly  
           arr[i] = i + 1;
       }
       console.log(arr);

Filter array

Elements greater than or equal to 10 are selected and put into a new array

// Method 1
 	var arr = [2, 0, 6, 1, 77, 0, 52, 0, 25, 7];
    var newArr = [];
    var j = 0;
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] > 10) {
              // The new array should be incremented from 0
              newArr[j] = arr[i];
              j++;
          }
      }
      console.log(newArr);
 // Method 2 
   var arr = [2, 0, 6, 1, 77, 0, 52, 0, 25, 7];
      var newArr = []; // newArr.length is 0
      for (var i = 0; i < arr.length; i++) {
          if (arr[i] > 10) {
              // The new array should be incremented from 0
              newArr[newArr.length] = arr[i];
          }
      }
      console.log(newArr);

Deletes the specified array element

// Delete 0
 var arr = [2, 0, 6, 1, 77, 0, 52, 0, 25, 7];
      var newArr = [];
      for (var i = 0; i < arr.length; i++) {
          if(arr[i] != 0) {
              newArr[newArr.length] = arr [i]
          }
      }
      console.log(newArr);

Flip array

     var arr = ['red', 'green', 'blue', 'pink', 'purple'];
     var newArr = [];
     for (var i = arr.length - 1; i >= 0; i--) {
         newArr[newArr.length] = arr[i]
     } 
     console.log(newArr);

Array sort (bubble sort)

Sort and display a series of data in a certain order

 		var arr = [5, 4, 3, 2, 1];
        for (var i = 0; i <= arr.length - 1; i++) { 
        // Number of outer circulating pipe trips
            for (var j = 0; j <= arr.length - i -1; j++) {
             // Exchange times of inner layer circulating pipe
                 // Internally exchange the values of 2 variables
                 if (arr[j] > arr[j+1]) {
                     var temp = arr[j];
                     arr[j] = arr[j+1];
                     arr[j+1] = temp;
                 }
            }
        }
        console.log(arr); // 1,2,3,4,5
       
 		var arr = [4, 5, 3, 1, 2];
        for (var i = 0; i <= arr.length - 1; i++) { 
        // Number of outer circulating pipe trips
            for (var j = 0; j <= arr.length - i -1; j++) {
             // Exchange times of inner layer circulating pipe
                 // Internally exchange the values of 2 variables
                 if (arr[j] < arr[j+1]) {
                     var temp = arr[j];
                     arr[j] = arr[j+1];
                     arr[j+1] = temp;
                 }
            }
        }
        console.log(arr); // 5,4,3,2,1

JavaScript function

A function encapsulates a block of code that can be repeatedly called and executed.
The goal is to reuse a lot of code

 function getSum(num1,num2) {
            var sum = 0;
            for (var i = num1;i <= num2;i++) {
                sum += i;
            }
            console.log(sum);
        }
        getSum(1, 100);

Function use

Declaring and calling functions
Function encapsulation is to encapsulate one or more functions through functions

// Declarative function
function Function name() {
	// Function body
}
// Function names are usually verbs
// Functions do not call and do not execute themselves
 Function name(); // Call function

 function sayHi() {
           console.log('hi~');
       }
       sayHi();

case

Use the function to calculate the cumulative sum between 1-100

			function getSum() {
            var sum = 0;
            for (var i = 1;i <= 100;i++) {
                sum += i;
            }
            console.log(sum);
        }
        getSum();

Parameters of function

Use the parameters of the function to repeat different codes

function Function name(Formal parameter 1,Formal parameter 2...) {

}
Function name(Argument 1,Argument 2...);
 function cook(aru) { // The formal parameter aru can be regarded as an undeclared variable
          console.log(aru);
      }
  cook('sour and spicy shredded potatoes');
  cook('Big elbow');
 // The parameters of the function can be or not, and the number is unlimited
 // Multiple parameters are separated by commas

case

Using function to find the sum between any two numbers

The number of function parameters and arguments matches

  function getSum(num1, num2) {
            console.log(num1 + num2);
        }
        console.log(1, 2); // If the number of arguments is consistent with the number of formal parameters, the result will be output normally
        console.log(1, 2, 3); // If the number of arguments is more than the same as the number of formal parameters, the number of formal parameters will be obtained
        console.log(1); // If the number of arguments less than the number of formal parameters is consistent, the more formal parameters are defined as undefined, and the final result is NaN

Summary

Return value of function

return statement

function Function name() {
	return Results to be returned;
}
Function name();
// The function only implements a certain function, and the final result needs to be returned to the caller of the function ()
// return returns the following result to the caller of the function 

 function getResult() {
           return 666;
       }
       getResult();
       console.log(getResult());

function cook(aru) { 
         return aru;
      }
      cook('Big elbow');
  console.log(cook('Big elbow'));

 function getSum(num1, num2) {
            return num1 + num2;
        }
        getSum(1, 2);

case

Using function to find the maximum of two numbers

 function getMax(num1, num2) {
       return  num1 > num2 ? num1 : num2;
      }

Find the maximum value in any array

 function getArrMax(arr) { // arr receives an array
            var max = arr[0];
       for (var i = 0; i < arr.length;i++) {
           if (arr[i] > max) {
               max = arr[i];
           }
       }
       return max; 
        }
        var re = getArrMax([1, 2, 5, 9, 10]);
        console.log(re);

return stop function

1. The code after return will not be executed
2.return can only return one value. The result is the last value

 function fn(num1, num2) {
           return [num1 + num2, num1 - num2, num1 * num2, num1 / num2];
       }
       var re = fn(1, 2);
       console.log(re); // 3. If you need to return multiple values, you can use an array

4. If the function does not return, it returns undefined
The difference between break, continue and return

Use of arguments

When we are not sure how many parameters are passed, we can use arguments to get them

 function fn() {
          console.log(arguments); 
          // All arguments passed are stored in the arguments object
          // Traversal array
            for (var i = 0; i < arguments.length;i++) {
         console.log(arguments[i]);
        }
      }
      fn(1, 2, 3);

Pseudo arrays are not real arrays
1. Have the length attribute of the array
2. Store by index
3. It does not have some methods of real array

case

Using function to find the maximum value of any number

function getMax() {
            var max = arguments[0];
            for (var i = 0; i < arguments.length; i++) {
                if(arguments[i] > max) {
                    max = arguments[i];
                }
            }
            return max;
        }
        console.log(getMax(1, 2, 3));
        console.log(getMax(1, 4, 6, 3));

Function case

1. Use function encapsulation to flip the array

 function reverse(arr) {
            var newArr = [];
            for (var i = arr.length - 1; i >= 0; i--) {
                newArr[newArr.length] = arr[i];
            }
            return newArr;
        }
        var arr1 = reverse([1, 3, 4, 6, 9]);
        console.log(arr1); // 9,6,4,3,1

2. Sort array -- bubble sort

function sort(arr) {
           for (var i = 0; i < arr.length - 1; i++) {
               for (var j = 0; j < arr.length - i -1; j++) {
                   if (arr[j] > arr[j + 1]) {
                       var temp = arr[j];
                       arr[j] = arr[j + 1];
                       arr[j + 1] = temp;
                   }
               }
           }
           return arr;
       }
       var arr1 = sort([1, 5, 4, 3, 6]);
       console.log(arr1); // 1,3,4,5,6

3. Judge leap year

 function isRunYear(year) {
           var flag = false;
           if (year %4 == 0 && year % 100 != 0 || year % 400 == 0) {
               flag = true;
           }
           return flag;
       }
       console.log(isRunYear(2000)); // true
       console.log(isRunYear(1999)); // false

Function can call another function

   // Functions can call each other
      function fn1() {
          console.log(11);
          fn2(); // The fn2 function is called in fn1.
      }
      fn1();

      function fn2() {
          console.log(22);
      }

The user inputs the year and outputs the days of the current February

function backDay() {
         var year = prompt('Please enter the year:');
         if (isRunYear(year)) {
             alert('There are currently 29 days');
         } else {
             alert('There are currently 28 days');
         }
     }
     backDay();

     // Judge whether it is a function of leap year
     function isRunYear(year) {
           var flag = false;
           if (year %4 == 0 && year % 100 != 0 || year % 400 == 0) {
               flag = true;
           }
           return flag;
       }

Two declaration methods of function

Named function

// Function expression syntax anonymous function
var Variable name = function() {};
Variable name(); // call
var fun = function() {
	console.log('I'm a function expression');
}
fun(); // fun is a variable name, not a function name
// Function expressions can also pass parameters

Scope

Code name (variable) plays a role and effect in a certain range
Objective to improve the reliability of the program and reduce the naming conflict
Before the scope of js (es6): global scope and local scope
Global scope: the entire script tag or a separate js file
Local scope: within the function, it only plays an effect and role within the function

var num = 10;
console.log(num);
function fn() {
	var num = 20;
	console.log(num);
}
fn();

Variables are divided into global variables and local variables
Global variables: variables under the global scope
If there is no declaration inside the function, the direct assignment is also a global variable (not recommended)
Local variable in function
The formal parameters of a function are also local variables

 function fun() {
         var num1 = 10;
         num2 = 20;
     }
     fun();
     console.log(num2);

js has no block level scope (before es6)
Block level scope {} if {} for {}

Scope chain

The internal function accesses the variables of the external function and adopts the chain search method

 var num = 10;
        function fn() { // External function
            var num = 20;

            function fun() { // Internal function
                console.log(num); // 20
            }
            fun();
        }
        fn();

Pre analysis

js engine runs js in two steps: pre parsing code execution
The js engine will promote the var and function in js to the front of the current scope
Code execution is executed from top to bottom
Pre parsing is divided into variable pre parsing and function pre parsing
Variable promotion promotes all variable declarations instead of the first assignment operation in the current scope

Topics: Javascript Front-end