Process control

Introduction to Process Control

  • Sequential structure

    • Code is executed from top to bottom, left to right.
    <script type="text/javascript">
    	var str = "From zero to one";
    	var str2 = "Series of books";
    	var str3 = str + str2;
    	console.log(str3);
    	document.write(str3);
    </script>
    Copy the code
  • Choose structure

    • Decide which piece of code to use based on conditional judgment.
  • Loop structure

    • Execute a piece of code repeatedly until the condition is not met.

Select the structure: if

One-way selection: if

  • Format:
    if(Condition) {}Copy the code
  • This “condition” is usually a comparison expression.
    var score = 100;
    if (score > 60) {
    	alert("Well, you're great.");
    }
    Copy the code

Two-way selection: if… else…

var score = 10;
if (score < 60) {
	alert("Make-up exam!);
} else {
	alert("Pass!);
}
Copy the code
  • Instead of bidirectional selection, you can use the ternary operator
var score = 100;
var result = (score < 60)?"Make-up exam! : "Pass!;
alert(result);
Copy the code

Multiple choices: if… else if… else…

var time = 14;
if (time < 12) {
	document.write("Good morning!);
} else if (time > 12 && time < 18) {
	document.write("Good afternoon!);
} else {
	document.write("Good evening!);
}
Copy the code

If statements are nested

var gender = "Female";
var height = 172;
if (gender == "Male") {
	if (height > 170) {
		document.write("Tall Boy");
	} else {
		document.write("Short Boy."); }}else {
	if (height > 170) {
		document.write("Tall Girl");
	} else {
		document.write("Short Girl"); }}Copy the code

Select structure: Switch

  • Don’t forget to write break
var day = 5;
var week;
switch (day) {
	case 1:
		week = "Monday";
	break;
	case 2:
		week = "Tuesday";
	break;
	case 3:
		week = "Wednesday";
	break;
	case 4:
		week = "Thursday";
	break;
	case 5:
		week = "Friday";
	break;
	case 6:
		week = "Saturday";
	break;
	default:
		week = "Sunday";
	
}
document.write(week); / / Friday
Copy the code

Loop structure: while

  • To execute a block of code repeatedly if a condition is met.
var n = 1;
var sum = 0;
while (n <= 100) {
	sum=sum+n;
	n++;
}
document.write("1 + 2 + 3 +... + 100 =", sum);
Copy the code

Loop structure: do… while

  • Do it one time and then judge
var n = 1;
var sum = 0;
do {
	sum += n;
	n++;
} while (n <= 100);
document.write("1 + 2 + 3... + 100 =", sum);
Copy the code

Loop structure: for

for (var i = 0; i < 5; i++) {
	document.write(i+"<br/>");
}
Copy the code

Determine whether a number is a whole number or a decimal number

Is a number an integer or a decimal?
// Use the parseInt and parseFloat methods
// If it is an integer, both methods return the same result; Otherwise it's a decimal
var n = 3.14;
if (parseInt(n.toString()) == parseFloat(n.toString())){
	document.write(n+ "Is an integer.");
} else {
	document.write(n + "It's a decimal.");
}

Copy the code

Title: Number of daffodils

  • The daffodil number is a 3-digit number whose cube sum is equal to the number itself. For example, 153 is a daffodil number because 153 = 13 + 53 + 33.
var str = "";
for (var i = 100; i < 1000; i++) {
	var a = i % 10; / / bits
	var b = (i / 10) % 10; / / 10
	b = parseInt(b); // Drop the decimal
	var c = parseInt(i / 100); / / one hundred
	
	if (i == (a*a*a + b*b*b + c*c*c)) {
		str += i + "、"; }}document.write(str);
// 1, 2, 3, 3, 4, 4,
Copy the code

New function

What is the function?

  • Let’s start with a piece of code
var sum = 0;
for (var i = 1; i <= 50; i++) {
	sum += i;
}
document.write("The sum of all integers up to 50 is:", sum);
Copy the code
  • The above code does the following: calculates the sum of all integers up to 50.

  • What if I wanted to sum all the numbers up to 100? Copy the code, and that’s done very quickly.

  • If you were asked to add up to 50, 100, 150, 200, and 250 integers, respectively. Wouldn’t you have to write the same code five times?

  • To reduce this burden of repetition, JS introduces the concept of functions.

// Define the function
function sum(n) {
	var m = 0;
	for (var i = 1; i <= n; i++) {
		m += i;
	}
	document.write(n+"The sum of all integers within:", m + "<br/>");
}

// Call the function
sum(50);
sum(100);
Copy the code
  • To use functions in JS, there are generally two simple 2-steps.
    • Define a function
    • Call a function

Definition of a function

  • In JS, functions can be divided into two kinds: one is a function with a return value; The other is a function that returns no value.

A function that has no return value

  • For parameters of a function, yes can be omitted, of course it can be 1, 2, or n.
// Define the function
function sum(a, b) { // The parameters here are parameters
	var sum = a + b;
	document.write(sum);
}

// Call the function
sum(1.2);// The arguments here are arguments
Copy the code
  • It makes no sense for a function to have only defined parts but no calling parts. If the function is defined and not called, JavaScript automatically ignores the function, which means it will not be executed. Functions are executed only when they are called.

A function that returns a value

  • A function that returns a value is a function that returns a value after it has been executed.
  • There is no return value, just a return statement.
// Define the function
function addSum(a,b) {
	var sum = a+b;
	return sum;
}

// Call the function
var n = addSum(1.2) + 100;
document.write(n);
Copy the code

Global and local variables

  • Depending on scope, variables can be divided into the following two types.

    • The global variable
    • A local variable
  • Global variables are generally defined in the main program and are valid from the beginning of the definition to the end of the program. Global variables can be used anywhere.

  • A local variable is defined in a function, and its valid scope is limited to the function.

var a = "十里";
// Define the function
function getMes() {
	var b = a + "Peach blossom";
	document.write(b);
}

// Call the function
getMes();
// Try using the variable b inside the function
document.write(b);
Copy the code

Function call

  • If a function is only defined and not called, the function itself will not be executed.
  • Js is very different from other programming languages (C, Java, etc.). Js function call methods, there are four common.

Direct call

// Define the function
function test() {
	document.write("Hello World");
}

// Call the function
test();
Copy the code

Called in an expression

// Define the function
function addSum(a,b) {
	var sum = a+b;
	return sum;
}

// Call the function
var n = addSum(1.2) + 100;
document.write(n);
Copy the code

Called in a hyperlink

  • Call the function using “javascript: function name” in the href attribute of the A element.
<a href="javascript:test()"> calls a function </a>Copy the code

Called in the event

  • Js is an event-based language. Mouse movement, click, and so on. But when an event occurs, we can call a function that responds to that event.
<input type="button" onclick="test()" value="Submit" />
<script type="text/javascript">
	function test() {
		alert("Study hard!");
	}
</script>
Copy the code

Nested function

  • To define another function inside a function. However, functions defined internally can only be called internally. If called externally, an error occurs.
// Define the factorial function
function func(a) {
	// The nested function definition calculates the squared function
	function multi(x) {
		return x * x;
	}
	var m = 1;
	for (var i = 1; i <= multi(a); i++) {
		m=m*i;
	}
	return m;
}
// Call the function
var sum = func(2) + func(3);
document.write(sum); / / 362904
Copy the code
  • In this example, the func() function defines a multi() inside.

  • Func (2) implements 1x2x3x4, which is 4 factorial. Similarly, func(3) implements 1x2x3… X9, which is 9 factorial.

  • Nested functions are very powerful and are directly related to the important JS concept of closures. For starters, all you need to know is that there are nested functions.

Built-in function

  • In JavaScript, functions can also be divided into “custom functions” and “built-in functions”.
  • Custom functions, that’s our custom functions, that’s what we learned before.
  • Built-in functions refer to functions that have been defined in JavaScript, that is, we do not need to write the function body, just call it.
// Function description
parseInt() Extracts numbers from a string, only integersparseFloat() Extract numbers from string, can extract decimalsisFinite() Determine whether a certain number is a finite numberisNaN() Check whether a number isNaNvalueescape() encodes the stringunescape() Decodes the stringevalExecute a string as if it were an expressionCopy the code

Question: Determine whether a certain year is a leap year

  • Leap years are judged by two factors.
    • For ordinary years, leap years are those that are integer by 4 and not divisible by 100
    • For century years, the ones divisible by 400 are leap years
// Define the function
function isLeapYear(year) {
	// Determine leap year conditions
	if ((year % 4= =0) && (year % 100! =0) || (year % 400= =0)) {
		return year + "Year is a leap year";
	} else {
		return year + "Year is not leap year."; }}// Call the function
document.write(isLeapYear(2018));
Copy the code

Title: Find the maximum of any 5 numbers

function getMax(a,b,c,d,e) {
	var maxNum;
	maxNum = (a > b) ? a : b;
	maxNum = (maxNum > c) ? maxNum : c;
	maxNum = (maxNum > d) ? maxNum : d;
	maxNum = (maxNum > e) ? maxNum : e;
	return maxNum;
}
document.write("The maximum of the 5 numbers is:" + getMax(3.9.1.12.50));
Copy the code
  • This is just to get you familiar with the function.

  • Functions are extremely complex, and we’ve only scratched the surface here.