Introduction to JavaScript -- process control statement & A case of classic algorithm

Posted by whizzkid-000 on Sun, 19 Dec 2021 16:36:26 +0100

Process control: Branch (condition), loop

1. Branch statement

1.1 conditional statements

if statement

The statement executes code only when the specified condition is true

if (condition)
{
    When the condition is true Code executed when
}

if... else statement

Use the if... else statement to execute code when the condition is true and other code when the condition is false.

if (condition)
{
    When the condition is true Code executed when
}
else
{
    When the condition is not true Code executed when
}

If... else if... else statement

Use the if... else if... else statement to select one of multiple code blocks for execution.

if (condition1)
{
		statement1
    When condition 1 is true Code executed when
}
else if (condition2)
{
		statement2
    When condition 2 is true Code executed when
}
else
{
		statement3
  	When neither condition 1 nor condition 2 is true Code executed when
}
switch Statements

Used to perform different actions based on different conditions

Use the switch statement to select one of multiple code blocks to execute

switch(n)
{
    case 1:
        Execute code block 1
        break;
    case 2:
        Execute code block 2
        break;
    default:
        And case 1 and case 2 Code not executed at the same time
}

default keyword

Use the default keyword to specify what to do when a match does not exist:

var d = new Date().getDay();
// Use the switch case statement to make a judgment
switch (obj) {
    case 0:
        console.log("Sunday");
        break;
    case 1:
        console.log("Monday");
        break;
    // case 2:
    //     console.log("Tuesday");
    //     break;
    case 3:
        console.log("Wednesday");
        break;
    case 4:
        console.log("Thursday");
        break;
    case 5:
        console.log("Friday");
        break;
    case 6:
        console.log("Saturday");
        break;
    // When all conditions are not met, execute default
    default:
        console.log("Looking forward to the weekend");
        break;
}

be careful:

  1. break in case code block cannot be omitted

  2. default can be placed anywhere in the code, break cannot be omitted, and break can be omitted in the last position;

  3. "Variable vs. constant"===“

Recommendations:

switch is recommended for branch control for equivalence comparison, and If is recommended for non equivalence judgment

Circular statement

Loop can specify the number of times the code block is executed.

Different types of loops

JavaScript supports different types of loops:

  • for - cycles a block of code a certain number of times
  • for/in - loop through the properties of the object
  • while - loop the specified code block when the specified condition is true
  • do/while - also loop the specified code block when the specified condition is true
for loop

The following is the syntax of the for loop:

for (*Statement 1*; *Statement 2*; *Statement 3*)
{
  *Executed code block*
}
for (var i=0; i<5; i++)
{
    console.log(i);
}

Statement 1 is executed before the start

Statement 2 defines the conditions for running a cyclic code block

Statement 3 executes after the loop code block has been executed

Algorithm case of for loop:

1-100 even sum

var result = 0;
for(var i=0;i<=100;i++){
  if(i%2==0){
  	result += i;
  }
} 
console.log(result);

Bubble sorting

//1. Compare two adjacent elements. If the former is larger than the latter, exchange the position.
//2. After the first round of comparison, the last element is the largest element.
//3. At this time, the last element is the largest, so the last element does not need to participate in the size comparison.
// First cycle
/* 19<11  false  [11,19,20,6,10]
   19<20  true   [11,19,20,6,10]
   20<6   false  [11,19,6,20,10]
   20<10  false  [11,19,6,10,20]*/

// Create a new method bubble sort
function bSort(arr) {
  // Define a variable to receive the length of the array
  var len=arr.length;
  // for loop to realize bubble sorting
  for(var i=0;i<len-1;i++)
  {
​    for(var j=0;j<len-1;j++)
​    {
​      // Compare the front and back elements if the front large swap position
​      if(arr[j]>arr[j+1]){
​        // Create an intermediate quantity for value conversion
​        var x=arr[j];
​        arr[j]=arr[j+1];
​        arr[j+1]=x;
​      }
​    }

  }
  // After sorting, the arr is returned
  return arr;
}
var arr=[19,11,20,6,10];
// console.log(bSort(arr));

Special for loop conditions

// There are commas in the comma effect condition. Finally, the rightmost condition (the condition closest to the semicolon) is used as the termination condition
for(i=0,j=0;i<10,j<18;i++,j++)
{
    x=i+j;
}
console.log(x);//34
Keyword break

If you want to exit before all iterations, you can use break. When the break is executed, it will immediately jump out of the loop body.

The difference between the keyword continue and break is that continue does not jump out of the loop. Instead, immediately end the current cycle and enter the next cycle.

For... in -- enhanced for loop

for... in is used to traverse the properties of an array or object

For (custom variable name in array / object){

Execute code

}

"Custom variable name" is used to specify the element index of the array or the attribute of the object

// for...in... loop
for (var arrIndex in bSort(arr)) {
    console.log(arrIndex + '---' + arr[arrIndex]);
}

while Loop

The while loop executes the code block when the specified condition is true

grammar

while (*condition*)
{
  *Code to execute*
}
while (i<5)
{
    console.log(i);
    i++;
}
// Find the sum of 1-100
var result=0;
// Starting condition
var i=1;
// Cycle end condition
while(i<=100)
{
    result+=i;
    // The starting condition is self increasing or self decreasing, which is written at the end
    i++;
}
console.log(result);

do-while Loop

The do/while loop executes the code once before checking whether the condition is true. Therefore, if the condition is false, it will also execute once. If the condition is true, the loop will be repeated.

do
{
    Code to execute
}
while (condition);
// Find the sum of 1-100
var result = 0;
var i = 1;
do{
	result += i;
	i++;
} while(i<=100);
console.log(result);

recursion

A process or function has a method to call itself directly or indirectly in its definition or description. It usually transforms a large and complex problem layer by layer into a smaller problem similar to the original problem. The recursive strategy can describe the multiple repeated calculations required in the problem-solving process with only a small number of programs, which greatly reduces the amount of code of the program.

//The function calls itself
//A jump out condition is required

// Recursive factorization
function fc(n) {
  // Jump out condition
  if(n==1)
  {
​    return 1;
  }
  // Factoring with recursion
  return fc(n-1)*n;
}
console.log(fc(10));

Algorithm instance expansion:

1. Factorial realization:

var n = 1;

// 1.while loop
var m1=1;
while (n <= 10) {
 var m1 = m1 * n
  n++;
}
console.log(m1);
// 2. Do while loop
var m2=1;
 do{
  var m2=m2*n;
   n++;
 }while(n<=10)

// 3.for loop
var m3=1;
 for(var n=1;n<=10;n++){
 var m3=m3*n;
}
console.log(m);
//Recursive Method 
function fc(n) {
  // Jump out condition
  if(n==1)
  {
​    return 1;
  }
  // Factoring with recursion
  return fc(n-1)*n;
}
console.log(fc(10));

2.99 implementation of multiplication table

// Using the for loop
 for (var n = 1; n <= 9; n++) {
 	for (var m = 1; m<=n ; m++) {
 		var result = n * m;
	 	document.write(m + '*' + n + '=' + result+'&nbsp;');
 	}
 	document.write("<br>");
 }
// Using do/while loop
var n = 9;
do {
	var m = 1;
	do {
		var result = n * m;
		document.write(m + '*' + n + '=' + result + '&nbsp;');
		m++;
	} while (m <= n)
	n--;
	document.write('<br>');
} while (n >= 1)
// Using while loop
var n = 9;        
while (n >= 1) {
	var m = 1;
	while (m <= n) {
		var result = n * m;
		document.write(m + '*' + n + '=' + result + '&nbsp;')
		m++;
	}
	n--;
	document.write('<br>');
}

3. Three digits of non repeating numbers composed of 1, 2, 3 and 4

var arr = [1, 2, 3, 4]
var sum =0;
for (var i = 0; i < arr.length; i++) {
    for (var j = 0; j < arr.length; j++) {
        if (i != j) {
            for (var k = 0; k < arr.length; k++) {
                if (j != k && i!=k) {
                    var result = arr[i] * 100 + arr[j] * 10 + arr[k];
                    console.log(result);
                    sum++;
                }
            }
        }
    }
}
console.log(sum);

4. Print out 101-200 prime numbers

var count = 0;
for (var i = 101; i <= 200; i++) {
    // var flag = true;
    for (var j = 2; j < i; j++) {
        var result = i % j;
        if (result == 0) {
            // flag = false;
            break;
        }
    }
    if (result != 0) {
        console.log(i);
        count++;
    }
}
console.log(count);

5. 100-1000 daffodils, e.g. 153 = 111 + 555 + 333

for (var i = 100; i < 1000; i++) {
    // Hundreds
    var num1=parseInt(i/100) ;
    // Ten digits
    var num2=parseInt((i%100)/10);
    // Single digit
    var num3=parseInt(i%100%10);

    var Num=Math.pow(num1,3)+Math.pow(num2,3)+Math.pow(num3,3);
    if(Num==i)
    {
        console.log(Num);
    }

}

6.1-1000 perfect number, for example, 6 = 1 + 2 + 3; 1, 2 and 3 are factors of 6;

for(var i=1;i<=1000;i++)
        {
            var sum=0;
            for(var j=1;j<i;j++)
            {
                if(i%j==0)
                {
                    sum+=j;
                }
            }
            if(sum==i){
                console.log(i);
            }
        }

Topics: Javascript node.js Algorithm