js basic syntax summary

Posted by djremiasz on Tue, 21 Dec 2021 20:15:20 +0100

js basic syntax summary

Tip: Author: Participant

Moral: those who meet will leave, one period and one prayer

preface

Tip: the following is the basis of JS syntax

Sort it out by yourself for centralized review

1, Variable

1 what are variables

A variable is a box of things

Amount of change, content of change, data of change

2 use of variables

First declare in assignment
Use the keyword var to declare
var variable name;
var age; // Declare a variable named age
Variable name = value;
age = 10; // Assign a value of 10 to this variable

=It is used to assign the value on the right to the variable space on the left. The equal sign here represents the meaning of assignment

var variable name = value;
var age = 18; // Declare the variable age and assign it to 18

It is called variable initialization

2, Data type

Simple data type (basic data type)

3, Process control

1 process control concept

Process control is to control the execution of code according to a certain structural order
There are three main structures of process control, namely sequence structure, branch structure and loop structure, which represent the execution order of the three codes
Analysis diagram:

2 branch process control

if statement

Grammatical structure
//If the condition is true, execute the code, otherwise do nothing
If (conditional expression / value / variable) {/ / for values and variables, if will be implicitly converted to boolean type***
//Code statement executed when the condition is satisfied
}

if (3 < 5) {
    alert('Desert camel ');
}

Statement: it can be understood as a behavior, which can be a line of code or a piece of code. Circular statements and branch statements are typical statements.
Code case:

//The prompt input box pops up, the user enters the age, and the program takes this value and saves it in the variable
//Use the if statement to judge the age. If the age is greater than 18, execute the output statement in the if braces
var age = prompt('Please enter your age:');
if (age >= 18) {//Here > = makes an implicit conversion to convert the age string 18 to the number 18
    alert('I want to take you to the Internet cafe to steal headphones');
}

if else statement (double branch statement)

Grammatical structure
//If the condition is true, execute the code in if, otherwise execute the code in else
if (conditional expression){
//[if] the condition is true, the code to be executed
} else {
//[otherwise] executed code
}
example

var age = prompt('Please enter+Enter your age:');
if (age >= 18) {
    alert('I want to take you to the Internet ba');
} else {//Else does not need to write conditions, because else is satisfied if it is not satisfied. The else condition is omitted (here, the else condition is age < 18)
    alert('Get out, ');
}

Judge leap year code cases

//Algorithm: leap years are those that can be divided by 4 and can not be divided by 100 (for example, 2004 is a leap year and 1901 is not a leap year) or those that can be divided by 400 are leap years
// Pop up the prompt input box, let the user enter the year, take this value and save it in the variable
// Use the if statement to judge whether it is a leap year. If it is a leap year, execute the output statement in if braces, otherwise execute the output statement in else
// Be sure to pay attention to the writing of and & & or 𞓜 in it, and pay attention to the way to judge the division is to take the remainder as 0
var year = prompt('Please enter the year:');
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
    alert('The year you entered is a leap year');
} else {
    alert('The year you entered is a normal year');
}

if else if statement (multi branch statement)

Grammatical structure
//Suitable for checking multiple conditions.
if (conditional expression 1){
Statement 1;
}else if (conditional expression 2){
Statement 2;
}else if (conditional expression 3){
Statement 3;
...
} else {
//None of the above conditions holds. Execute the code here
}

Judgment case

// According to the idea of judging from large to small
// Pop up the prompt input box, let the user enter the score, take the value and save it in the variable
// Use the multi branch if else if statement to judge the output of different values respectively
var score = prompt('Please enter a score:');// Here > =, if string is compared with number, implicit conversion will be performed***
if (score >= 90) {
    alert('Baby, you are my pride');
} else if (score >= 80) {
    alert('Baby, you're already great');
} else if (score >= 70) {
    alert('You have to keep refueling');
} else if (score >= 60) {
    alert('Boy, you're dangerous');
} else {
    alert('Bear boy, I don't want to talk to you. I just want to talk to you with a whip');
}

3 ternary expression (short for simple if else)

Grammatical structure
Expression 1 / value? Expression 2 / value: expression 3 / value;
If expression 1 is true, the value of expression 2 is returned; if expression 1 is false, the value of expression 3 is returned

code

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

Digital zero filling case

//The user enters a number between 0 and 59
// If the number is less than 10, fill 0 in front of this number (add 0 to splice), otherwise do not operate
// Accept the return value with a variable and output
var time = prompt('Please enter a 0 ~ 59 A number between');
// Ternary expression? Expression 1: expression 2 
var result = time < 10 ? '0' + time : time; //   Assign the return value to a variable
alert(result);

4. Switch branch process control

Grammatical structure

The switch statement is also a multi branch statement, which is used to execute different code based on different conditions.

When you want to set a series of options for a specific value for a variable, you can use switch.

Switch (expression) {/ / an expression is often a variable***
case value1: / / it is only a value, and writing an expression is not supported: > = value1***
//Code to execute when expression equals value1
break;
case value2:
//Code to execute when expression equals value2
break;
default:
//Code to execute when the expression is not equal to any value
break; // This can be omitted
}

example

switch (8) {
      case 1:
          console.log('This is 1');
          break;
      case 2:
          console.log('This is 2');
          break;
      case 3:
          console.log('This is 3');
          break;
      default:
          console.log('No matching results');

  }

Note: when executing the statement in the case, if there is no break, continue to execute the statement in the next case
Query fruit cases

//Pop up the prompt input box, let the user enter the fruit name, take this value and save it in the variable.
// Take this variable as the expression in switch brackets.
// Write several different fruit names in the value after case. Be sure to put quotation marks because it must be a congruent match.
// Just pop up different prices. Also note that each case is followed by a break to exit the switch statement.
// Set default to no such fruit.
var fruit = prompt('Please enter the fruit you want to query:');
switch (fruit) {
    case 'Apple':
        alert('The price of apple is 3.5/Jin');
        break;
    case 'Durian':
        alert('The price of durian is 35/Jin');
        break;
    default:
        alert('No such fruit');
}

4, Circulation

1 for loop

Grammatical structure
For (initialization variable; condition expression; operation expression){
//Circulatory body
}
example

for (var i = 1; i <= 100; i++) {
     console.log('how are you');
 }//i: iterator: iterator. Iteration is also called loop

Personal understanding

for (var i = 1; i <= 100; i++) {  
    console.log('how are you');//Circulatory body
    // Understanding of i: i is called a counter
    // for loop is to loop many times. To determine how many times to loop, you need to have a counter
    // Cycle once, i needs to add 1
}
/*1. initialization: var i = 1 
Initialize variables. Initialization is performed only once. (if executed multiple times, the loop will be closed)
2. Conditions: i <= 100 
i Once the value of is changed, the conditional expression must be judged: i <= 100 Is it established
3. Circulatory body
 Once the conditional expression is established, the loop body is executed. Otherwise, do not execute.
4. Operation expression: i++
The last operation expression: i++,because i If it does not change, it will always be 1, which is an endless cycle.
After the operation expression is executed, i It has changed again, so go to step 2.

2 double for loop

  • Loop nesting refers to defining the syntax structure of a loop statement in a loop statement
  • For example, in a for loop statement, another for loop can be nested. Such a for loop statement is called a double for loop.
    Double for loop syntax
    for (initial of outer loop; condition of outer loop; operation expression of outer loop){
    for (initial of inner loop; condition of inner loop; operation expression of inner loop){
    Code to be executed;
    }
  • The inner loop can be regarded as the statement of the outer loop
  • The execution order of the inner loop should also follow the execution order of the for loop
  • The outer loop is executed once, and the inner loop is executed all times
    -Example:
 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 inner circle' + j + 'second');

     }
 }

Core logic:

  • Inner loop control column, outer loop control row
  • The outer loop and inner loop cannot use the same counter. Generally, i is used externally and j is used internally (programmer's habit)
    for loop summary
  • The for loop can repeat some of the same code
  • The for loop can repeat a little different code because we have counters
  • The for loop can repeat certain operations, such as arithmetic operators and addition operations
  • As the demand increases, the dual for loop can do more and better results
  • Double for loop, the outer loop is executed once, and the inner for loop is executed completely
  • The for loop is a loop whose condition is directly related to the number

3 while loop

while statement can execute a specified piece of code in a loop on the premise that the conditional expression is true, and end the loop until the expression is not true.
The syntax structure of the while statement is as follows:
while (conditional expression){
//Loop body code
}
example

var num = 1;
while (num <= 100) {
    console.log('OK, yes');
    num++;
}

Implementation idea:

  • Execute the conditional expression first. If the result is true, execute the loop body code; If false, exit the loop and execute the following code
  • Execute loop body code
  • After the execution of the loop body code, the program will continue to judge the execution condition expression. If the condition is still true, the loop body will continue to be executed until the loop condition is false
    be careful:
  • When using a while loop, you must pay attention to that it must have exit conditions, otherwise it will become an endless loop
  • The difference between the while loop and the for loop is that the while loop can judge more complex conditions, such as user name and password

4 do while loop

  • The do... While statement is actually a variant of the while statement.
  • The loop will execute the code block once, and then judge the conditional expression. If the condition is true, the loop body will be executed repeatedly, otherwise exit the loop.
  • The syntax structure of the do... while statement is as follows:
do {
    // Loop body code - repeats the loop body code when the conditional expression is true
} while(Conditional expression);
var i = 1;
do {
    console.log('how are you?');
    i++;
} while (i <= 100)

Note: execute the loop body first, and then judge. The do... while loop statement will execute the loop body code at least once

Code case

// while loop case
// 1. Print one's life, from 1 year old to 100 years old
var i = 1;
do {
    console.log('This man this year' + i + 'Years old');
    i++;
} while (i <= 100)
// 2. Calculate the sum of all integers between 1 and 100
var sum = 0;
var j = 1;
do {
    sum += j;
    j++;
} while (j <= 100)
console.log(sum);

// 3. Pop up a prompt box, do you love me? If you enter I love you, you will be prompted to end. Otherwise, keep asking.
do {
	var message = prompt('Do you love me??');
} while (message !== 'I love you!')
alert('I love you too');

5 cycle summary

  1. Determine the number of cycles Cyclic conditions are generally a range
  2. Uncertain cycle times or cycle conditions can be complex
    while: judge first, then do
    do while: do it first and then judge (execute it first to know whether to start the cycle, such as: do you love me?)
  3. In most cases, for is used, while the application scenario is: write an endless loop

5, Array

1 concept of array

  • Array can store a group of related data together and provide convenient access (acquisition) mode
  • An array is a collection of data, each of which is called an element (item)
  • Any type of element can be stored in the array
    • Any type of element can be stored in an array, but we usually store a group of related data with the same data type
  • Arrays are an elegant way to store a set of data under a single variable name
  • Understanding of arrays: data combination, data set

2 create array

Create an array with new

var Array name = new Array() ï¼›
var arr = new Array();   // Create a new empty array

Note: Array(), A should be capitalized

Creating arrays with array literals

//1. Create an empty array using array literal
var  Array name = []ï¼›
//2. Create an array with initial value using array literal
var  Array name = ['Xiaobai','Little black','chinese rhubarb','Ritchey '];
  • The literal of the array is square brackets []
  • Declaring an array and assigning values is called array initialization
  • This literal way is also the way we use most in the future
    Array can store any type of data, such as string, number, Boolean value, etc.

3 get the elements in the array

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

// Define array
var arrStus = [1,2,3];
// Gets the second element in the array
alert(arrStus[1]);

6, Functions

1 concept of function

In JS, many codes with the same or similar functions may be defined, and these codes may need to be reused
Function: encapsulates a code block that can be repeatedly called and executed. Through this code block, a large amount of code can be reused

2 use of functions

Using steps: declaring and calling functions

Declarative function

The syntax is as follows:

// Declarative function
function Function name() {
    //Function body code
}

Note: since functions are generally defined to implement a function, we usually name the function as a verb, such as getSum
example

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

Call function

*-The syntax is as follows:

// Call function
 Function name(); 
  • Note: declaring the function itself will not execute the code, and the function body code will be executed only when the function is called.
  • Pithy formula: functions are not called, and they do not execute themselves
    example
function sayHi() {
    console.log('hi~~');
}
sayHi();

3 parameters of function

Function of parameters: some values cannot be fixed inside the function. We can pass different values when calling the function through parameters
Syntax of function parameters:

// Function declaration with arguments
function Function name(Formal parameter 1, Formal parameter 2 , Formal parameter 3...) { // You can define as many parameters as you want, separated by commas
  // Function body
}
// Function call with arguments
 Function name(Argument 1, Argument 2, Argument 3...); 
  1. When the function is called, the argument value will be passed to the formal parameter
  2. Formal parameters are simply understood as variables that do not need to be declared

Two declarations of functions

1. Custom function mode (named function)

// Declaration definition method
function fn() {...}
// call  
fn();

2 function expression mode (anonymous function)

// This is a function expression. Anonymous functions end with a semicolon
var fn = function(){...}ï¼›
// The function call must be written below the function body
fn();

7, Object

1. Related concepts of objects

In JavaScript, an object is an unordered collection of related attributes and methods. All things are objects, such as strings, values, arrays, functions, etc.
Objects are composed of properties and methods

  • Attribute: the characteristic of a thing, which is represented by an attribute in an object (a common noun)
  • Method: the behavior of things is expressed by method in the object (commonly used verb)

    In order to better store a group of data, the object came into being: the attribute name is set for each data in the object, which can access the data more semantically, the data structure is clear, the meaning is obvious, and it is convenient for developers to use
  • The variables in the object are called properties
  • The function in the object is called a method

2 three ways to create objects

1 create objects with literals

The syntax is as follows

var obj = {key:value,key2:value2...};

The code is as follows

var star = {// star is the object created.
    name : 'pink',
    age : 18,
    sex : 'male',
    sayHi : function(){
        alert('Hello, everyone~');
    }
};

Use of objects

//1. Dot syntax: object attribute
console.log(star.name)
//2. Bracket syntax: Object ['attribute']
console.log(star['name'])//star[name], first find the value of the name variable: 'age', star ['age '] --- 18
//1. Dot syntax: object Method ()
star.sayHi(); // When calling a method, be careful not to forget to bring the following parentheses
//2. Bracket syntax: Object ['method'] ()
star['sayHi']();

2 create an object using new Object

Create an empty object

var andy = new Object();

Sample code

andy.name = 'pink';//Add the name attribute to andy and assign a value
andy.age = 18;
andy.sex = 'male';
andy.sayHi = function(){//Add the sayHi method to andy and assign a value
    alert('Hello, everyone~');
}

Case:

//Please create a Naruto object in the form of new Object.   
//The details are as follows:  
//Name: Naruto  
//Gender: Male 
//Age: 19  
//skill: Shadow separation
var nld = new Object();
nld.name = 'Naruto';
nld.sex = 'male';
nld.age = 19;
nld.skill = function() {
	alert('Seduction');
}

3 create objects using constructors

Why do I need a constructor

  • Because we create one object at a time, many of its properties and methods are the same, and we can only copy them
  • Therefore, we can use function to encapsulate these repeated codes
  • Because this function is different, it encapsulates not ordinary code, but the code that creates the object, so it is called constructor
  • Constructor is to abstract some of the same properties and methods in our object and encapsulate them into functions
  • Constructor: a special function that can construct an object (create an object)

grammar
The syntax for defining the constructor is as follows:

function Constructor name(Formal parameter 1,Formal parameter 2,Formal parameter 3) {// The shape of the constructor is consistent with the common properties of the participating object
     this.Property name 1 = Formal parameter 1;//A formal parameter is to assign a value to an attribute
     this.Property name 2 = Formal parameter 2;
     this.Property name 3 = Formal parameter 3;
     this.Method name = Function body;//The function body does not need to be passed
}

Constructor call syntax: call through new

var obj = new Constructor name(Argument 1, argument 2, argument 3)

matters needing attention

  1. Constructor conventions are capitalized.
  2. this needs to be added in front of the properties and methods in the function to represent the properties and methods of the current object.
  3. return is not required in the constructor.
  4. When we create an object, we must call the constructor with new.

example

//Requirements: define a human constructor. The created human object contains attributes: name, age, gender, method: say hello.
function Person(name, age, sex) {   //***The parameters of the constructor are consistent with the ordinary properties of the object.
   // 1. Create the object this JS and do the first thing inside***
   //var  this = new Object();
   this.name = name;// The values of attributes are assigned by formal parameters with the same name
   this.age = age;
   this.sex = sex;
   this.sayHi = function() { //Functions do not need to be assigned by formal parameters
       alert('My name is:' + this.name + ',Age:' + this.age + ',Gender:' + this.sex);
   }
   //return this;    2. The second thing JS does internally***
}
// Create a big white human object. The name of big white is big white, 100, male
var bigbai = new Person('Big white', 100, 'male'); // var bigbai = this; 
// This is the big white object to be created. / / this: this, this object
console.log(bigbai.name);// Big white

var smallbai = new Person('Xiaobai', 21, 'male');
console.log(bigbai.name);
console.log(smallbai.name);

Code case

//Star constructor
function Star(name, age, sex) {
    this.name = name;
    this.age = age;
    this.sex = sex;
    this.sing = function(sang) {
        console.log(sang);

    }
}
var ldh = new Star('Lau Andy', 18, 'male'); 
console.log(ldh.name);
console.log(ldh['sex']);
ldh.sing('Ice rain');

Differences between constructors and objects

  • Constructors, such as Stars(), abstract the common part of the object and encapsulate it into functions. It generally refers to a large class
    Creating objects, such as new Stars(), specifically refers to a (specific) object. The process of creating objects through the new keyword is also called object instantiation
  • Example: it is the actual example (the actual example in a large class)

3 built in objects

Math object

The Math object is not a constructor, it has properties and methods of mathematical constants and functions. Math related operations (absolute value, rounding, maximum value, etc.) can use members in math.

example

console.log(Math.PI); // An attribute pi
console.log(Math.max(1, 99, 3)); // 99
console.log(Math.max(-1, -10)); // -1
console.log(Math.max(1, 99, 'pink teacher')); // NaN
console.log(Math.max()); // -Infinity

example

// 1. Absolute value method
console.log(Math.abs(1)); // 1
console.log(Math.abs(-1)); // 1
console.log(Math.abs('-1')); // Implicit conversion converts string - 1 to number
console.log(Math.abs('pink')); // NaN 

// 2. Three rounding methods
// (1) Math.floor() rounded down to the smallest value
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() is rounded. All other numbers are rounded, but. 5 is special. It takes the larger one  
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

Date object

Introduction:

  • Date object is different from Math object. Date is a constructor
  • Therefore, the specific methods and properties can only be used after instantiation
  • The Date instance is used to process Date and time

Get current time must be instantiated

var now = new Date();//Date object corresponding to current time

Gets the date object for the specified time

var time = new Date('2021/8/18');//Specify the date object corresponding to the time

example:

// Date() Date object is a constructor. We must use new to call to create our date object
var arr = new Array(); // Create an array object
var obj = new Object(); // An object instance was created
// 1. Use Date. If there is no parameter, return the current time of the current system
var date = new Date();
console.log(date);
// 2. The common writing method of the parameter is numeric 2019, 10, 01 or string '2019-10-1 8:8:8'
var date1 = new Date(2019, 10, 1);
console.log(date1); // November is returned, not October 
var date2 = new Date('2019-10-1 8:8:8');
console.log(date2);

Methods and properties of date objects:

Code case:

// Countdown effect
// 1. Core algorithm: the input time minus the current time is the remaining time, that is, the countdown, but you can't subtract the hours, minutes and seconds. For example, if you subtract 25 minutes from 05 minutes, the result will be negative.
// 2. Do it with time stamp. The total number of milliseconds of the user input time minus the total number of milliseconds of the current time is the number of milliseconds of the remaining time.
// 3. Convert the total milliseconds of the remaining time into days, hours, minutes and seconds (the timestamp is converted to minutes and seconds)
// The conversion formula is as follows: 
//  D = parseInt (total seconds / 60 / 60 / 24)// Calculation days
//  H = parseInt (total seconds / 60 / 60% 24) / / calculate hours
//  M = parseInt (total seconds / 60% 60)// Calculate score
//  S = parseInt (total seconds% 60)// Calculate current seconds
function countDown(time) {
    var nowTime = +new Date(); // Returns the total number of milliseconds of the current time
    var inputTime = +new Date(time); // Returns the total number of milliseconds of user input time
    var times = (inputTime - nowTime) / 1000; // times is the total number of seconds remaining 
    var d = parseInt(times / 60 / 60 / 24); // day
    d = d < 10 ? '0' + d : d;
    var h = parseInt(times / 60 / 60 % 24); //Time
    h = h < 10 ? '0' + h : h;
    var m = parseInt(times / 60 % 60); // branch
    m = m < 10 ? '0' + m : m;
    var s = parseInt(times % 60); // Current seconds
    s = s < 10 ? '0' + s : s;
    return d + 'day' + h + 'Time' + m + 'branch' + s + 'second';
}
console.log(countDown('2019-5-1 18:00:00'));
var date = new Date();
console.log(date);

Array object

Literal method:

var arr = [1,"test",true];

new Array() method:

var arr = new Array();

example:

// Two ways to create arrays
// 1. Use array literal
var arr = [1, 2, 3];
console.log(arr[0]);

// 2. Use new Array()
// var arr1 = new Array();  //  An empty array was created
// var arr1 = new Array(2);  //  This 2 indicates that the length of the array is 2 and there are 2 empty array elements in it 
var arr1 = new Array(2, 3); // Equivalent to [2,3], it means that there are two array elements, 2 and 3
console.log(arr1);

String object

  • Due to the immutability of the string, all methods of the string will not modify the string itself, and a new string will be returned after the operation is completed
  • String immutability means that the string itself will not change in memory
  • The value stored in the string variable can be changed

summary

The content of the article is limited, mainly to straighten out ideas

For details, please learn in combination with code and W3C

I wish you all success in your career

Topics: Javascript Front-end