The fourth day in the front end of Le byte learning - javaScript learning

1, Introduction

1. Overview:

JavaScript is an indispensable script language in current web development. js can run without compilation. It runs on the client and needs to parse and execute JavaScript code through the browser.

It was born in 1995. The main purpose at that time was to verify whether the data in the form was legal.

JavaScript should have been called Livescript, but on the eve of release, I wanted to catch a ride with the super hot java at that time and temporarily changed the name to JavaScript. (in other words, js has nothing to do with java. At that time, it just wanted to take advantage of java's reputation).

js components:

(1) ECMAScript: this part is mainly about the basic syntax of js.

(2) BOM: browser object model, which is mainly used to obtain browser information or operate the browser, such as forward and backward of the browser, pop-up prompt box of the browser, input URL jump in the browser address bar, etc.

(3) DOM: Document Object Model. The document here is temporarily understood as html. html is loaded into the memory of the browser. You can use js DOM technology to modify the html node in the memory. What users see from the browser is the page dynamically modified by JS. (addition, deletion, modification and query)

2. Features:

  1. Interactivity (what it can do is the dynamic interaction of information)
  2. Security (direct access to local hard disk is not allowed)
  3. Cross platform (any browser that can parse js can execute, regardless of the platform)

3. Differences between and Java:

javascript: Netscape's product, originally called Livescript. It is a literal translation language, weak type language

Java: the product of Sun company, now the product of Oracle company. It needs to be compiled into bytecode file before execution. Strongly typed language

4. Function

avaScript is used to improve design, validate forms, detect browsers, create cookies, and so on. JavaScript is the most popular scripting language on the Internet and can run in all major browsers, such as Internet Explorer, Maxthon, Mozilla, Firefox, Netscape, Chrome and Opera.

In the current learning stage, just remember the two most commonly used: (1) modify html and css code in operation state (2) verify the form

5. Writing position

5.1. Embedded type:

In theory, js can be written anywhere on the page.

<script>

alert("embedded")

</script>

5.2. External chain type:

First, create a new file of type js file, and then write js statements in the file, which are introduced into the html page through script tag pairs.

< script SRC = "js file path address" > js statements cannot be written here < / script >

5.3. Inline:

Writing directly on the label is a short event, so it is also called event attribute. onclick click event

< input type = "button" value = "point me!" onclick="alert('What am I doing! ^ 6 ^ '); >

< button onclick = "alert ('congratulations, 5 million. '); > Order me</ button>

6. Note:

Single line comment: / / comment statement shortcut key ctrl+/

Multiline comment: / comment statement / shortcut key ctrl+shift+/

Note: multi line comments cannot be nested with each other. Only single line comments can be used in multi line comments!

7. Data type:

Data types in Js:

Numeric type: number (all numbers are numeric and do not distinguish between integers and decimals)

String: string (all contents enclosed in quotation marks are strings)

boolean: boolean (true, false)

Object type: object (special value null)

Undefined type: undefined

Compare the data types in java:

Integer: byte short int long

Decimal: float double

Character: char

boolean: boolean

String: String

8. Variable:

8.1 definition: it is used to store data. Internal therapy can store any data

8.2. Declared variables:

var variable name = stored data; (variable variable)

8.3. Variable naming specification:

  1. Can only be composed of letters, numbers_ (underscore) and $(dollar sign).

  1. Cannot start with a number.

  1. The name cannot appear - (js will be understood as a minus sign for subtraction) and cannot conflict with the keyword.

js is a weakly typed language and does not pay attention to the definition of type, but js will determine the type of the variable according to the assignment of the variable:

Numerical type: var i = 1; var d = 2.35;

String: var str = "study hard";

Boolean: var b = true;

Contrast Java:java is a strongly typed language and pays attention to the definition of types. The types defined by Java are as follows:

Integer: int i = 1;

Floating point type: double d = 2.35;

String: String str = "study hard";

Boolean: boolean b = true;

Summary: definition of variables in js. Just add a var. java defines what type of variables to use.

9. Test data type:

typeof(value); Or typeof value; Returns the type of this variable

Note: different types of data can be assigned to the same variable

<script type="text/javascript">

var a;
alert(typeof a);  // undefined
a = 998;
alert(typeof a); // number
a = "study hard";
alert(typeof a); // string
a = true;
alert(typeof a); // boolean

</script>

10. Arithmetic operator

      • / % ++ --

be careful:

  1. Since both decimal and integer in js are of number type, there is no conclusion like whether an integer is divided by an integer or an integer.

  1. String and other data use the + sign operation, which will be connected into a new string.

  1. Strings use operators other than +: if the string itself is a number, it will be automatically converted to number for operation


Otherwise, a Nan result will be returned, indicating that this is not a number. NaN: not a number

<script>

alert(1234 / 1000 * 1000); // 1234
var s = "12";
s -= 10;
alert(s);  // 2
var s = "aa";
s -= 10;
alert(s); / / NaN Not a Number is Not a Number
var s = "12";
s += 10;
alert(s);       // 1210

</script>

11. Relational (comparison) operator

= < <= !=


==Equal to (compare contents only) = = = equal to (compare data types while comparing contents)


Note: the relational operator returns only two results: true / false

<script>

//Ask 1: 3 > 5, the result is?
alert(3 > 5);   // false

//Ask 2: "22" = = 22. What is the result?
alert("22" == 22); // true (value only)

//Ask 3: "22" = = 22. What is the result?

alert("22" === 22); // false (identical to, value and type must be equal)


</script>

12. Logical operator

&&And true & & false = = = = = = > false

||Or true|false = = = = = = > true

! No! true ====>false

False (understanding): false, 0, null, undefined

True (understanding): true, non-0, non null, non undefined

For & & doggerel: find the first false value (a false is a false)

For doggerel: find the truth value of the first occurrence (one true is one true)

Demo 1:

<script>

// Short circuit and (one false is false)

// Pithy formula: find the first false value

// What is the result of 1: 8 < 7 & & 3 < 4?

alert(8 < 7 && 3 < 4);  // false

// Excuse me, 2: - 2 & & 6 + 6 & & null result?

alert(-2 && 6 + 6 && null); // null

// What is the result of 3: 1 + 1 & & 0 & & 5?

alert(1 + 1 && 0 && 5); // 0

</script>

Demo 2:

<script>

// Short circuit or: one true is true

// Pithy formula: find the first value that is true

// What is the result of 1: 0 | 23?

alert(0 || 23); // 23

// Question 2: what is the result of 0 | false | true?

alert(0 || false || true); // true

// Ask 3: what is the result of null | 10 < 8 | 10 + 10?

alert(null || 10 < 8 || 10 + 10);  // 20

// Ask 4: null | 10 < 8 | false. What is the result?

alert(null || 10 < 8 || false); // false

</script>

13. Ternary operator:

Conditions? Expression 1: expression 2

If the condition is true, the result of expression 1 is returned

If the condition is false, the result of expression 2 is returned

demonstration:

<script>

// Excuse me 1: 3? "aaa": "bbb" the result is?

alert(3 ? "aaa" : "bbb");       // aaa

// Excuse me 2: 0? "ccc": "ddd" the result is?

alert(0 ? "ccc" : "ddd");       // ddd

</script>

14. if conditional statement

This is the same as the if statement in Java.

demonstration:

<script>

  var score = 59;

  if (score >= 90) {

      alert("excellent");

  } else if (score >= 80) {

      alert("good");

  } else if (score >= 60) {

      alert("pass");

  } else {

      alert("fail,");

  }

</script>

15. switch branch structure

This is the same as the switch structure in Java. Only the expressions in Java are: constant integer (to long), character and string

demonstration:

<script>

  var score = 59;

  // Requirement: an integer value will be required, no decimal point is required

  // parseInt method of window object

  score = window.parseInt(score / 10 + "");

  // alert(score);

  switch (score) {

      case 10:

      case 9:

          alert("excellent!");

          break;

      case 8:

          alert("good!");

          break;

      case 7:

      case 6:

          alert("pass!");

          break;

      default:

          alert("fail,!");

          break;

  }

</script>

16. Loop structure while, do while for;

While (loop condition) {loop body;}

do {circular body;} While (cycle condition);

For (initial value of loop variable; loop condition; loop variable increment) {loop statement;}

console.log(...); Output the results on the console in the form of log!

demonstration:

<script>

// Demand: count the number of numbers between 1 and 100 that can be divided by 3 and 7
var count = 0;


// 1. Traverse all integer values between 1 and 100

for (var i = 1; i <= 100; i++) {

    // 2. Judgment

    if (i % 3 == 0 && i % 7 == 0) {

        // alert(i);

        console.log(i);

        // 3. Cumulative number

        count++;

    }

}







// 4. View results

// alert(count);

console.log(count);




console. The log is displayed as follows:

21 42 63 84 4

17. Loop nesting

Demonstration case 9 * 9 multiplication table

<style>

    table {

        /* Change the line of table into thin line */

        border-collapse: collapse;

        /*color: red;*/

        border-color: red;

    }

</style>

<script>







    // Demand: 99 multiplication formula table

    document.write("<table border='1px solid red' cellspacing='0' cellpadding='8px'>");

    document.write("<caption>99 multiplication formula table</caption>");

    for (var i = 1; i <= 9; i++) {

        document.write("<tr>");

        for (var j = 1; j <= i; j++) {

            document.write("<td>");

            document.write(j + "*" + i + "=" + (j*i) + "&nbsp;&nbsp;&nbsp;&nbsp;");

            document.write("</td>");

        }

        document.write("</tr>");

    }

    document.write("</table>");

</script>




18. Custom function

Functions are named independent statement segments that can be referenced and executed as a whole:

Format:

Function function name (formal parameter) {function body}

Calling function: function name (actual parameter);

18.1. The function can only be executed after being called

18.2. If a function needs a return value and returns directly with return, it will not consider the type of return value like java

<script type="text/javascript">

// Define a function: function

function demo2() {

    return 666;

}

// Call function:

alert(demo2());

</script>

18.3. If the function needs to pass parameters and does not need to specify the type of parameters, it is OK to use variables directly

<script type="text/javascript">

// Define a function: function

function demo3(a, b) {

    return a + b;


}

// Call function:

alert(demo3(10, 20));//Display 30

</script>

18.4. Two function names with duplicate names appear in js, and the latter will overwrite the previous one

Compared with java, java has overloading (different parameters with the same name) and rewriting (different return value types and method bodies with the same name and parameter)

demonstration:

<script type="text/javascript">

// Define a function: function


function demo4(a, b) {


    alert("Call 1...");

}

function demo4() {

   alert("Call 2...");

}

demo4(10, 20);

demo4();

</script>

The page will show call 2

19. Anonymous function

Anonymous functions are functions without names

Function (formal parameter) {function body}

Calling method: assign an anonymous function to a variable and call the function through the variable name

Define function and assign value to variable: VAR FN = function (formal parameter) {function body}

Calling function: FN (actual parameter);

demonstration:

<script type="text/javascript">

// Anonymous function: function without name

var func = function(i, u) {

    alert(i + " love " + u);

}

// Call function:

func("Liuyan", "Xiaobai")// Show Liuyan love Xiaobai

</script>

20. Case - rotation chart

Note 1: the script tag needs to be placed after the body tag

Description 2: window Setinterval ("string function name ()", time milliseconds);

Description 3: window Setinterval (function name, time, milliseconds);

Description 4: window Setinterval (anonymous function, time milliseconds); Recommended use

<head>

<meta charset="UTF-8">

<title>Rotation map</title>

<style>

    div {

        width: 80%;

        margin: 50px auto;

    }

    img {

        width: 100%;

    }

</style>

</head>

<body>

<div class="container">

    <img src="../img/01.jpg" alt="picture">

</div>

</body>

Realize one:

<script>

// Requirement: get img tag in the page dynamically, and then modify src attribute of img tag

// 1. Get img tag

var img = document.getElementById("img");

// alert(img);

// Define a variable

var count = 1;

// 1.2 define a function

function changeImageSrc() {

    count++;

    img.src = "../img/0"+count+".jpg";

    // judge

    if (count == 8) {

        count = 0;

    }

}

// 2. Cycle and switch pictures

// window. Setinterval (function, time in milliseconds); In the specified time interval of milliseconds, the function passed in by the first parameter is called continuously

// Call method 1:

// window.setInterval("changeImageSrc()", 1000);

// Call mode 2:

window.setInterval(changeImageSrc, 1000);

</script>

Realization 2:

<script>

// Requirement: get img tag in the page dynamically, and then modify src attribute of img tag

// 1. Get img tag

var img = document.getElementById("img");

// alert(img);

// Define a variable

var count = 1;

// 2. Cycle and switch pictures

// window. Setinterval (anonymous function, time in milliseconds); In the specified time interval of milliseconds, the anonymous function passed in by the first parameter is called continuously

window.setInterval(function() {

    count++;
    
    img.src = "../img/0"+count+".jpg";

    // judge

    if (count == 8) {

        count = 0;

    }

}, 1000);

</script>

21. js event

21.1. Event overview:

Three elements of the event:

  1. Event source: the monitored html element (to whom this event is added) is a (some) html tag
  2. Event type: a certain type of action, such as click event, move in and remove event, keyboard tapping event, etc
  3. Execution instruction: the code to be executed after the event is triggered, which is generally encapsulated by functions

Syntax format: event source Event type = execute instruction

Case:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>event</title>

<script>

    // Window: the window object provides an event type onload page loading completion event

    // Event source: window event type: page load completion event (onload) execution instruction: it is the function function of assignment

    window.onload = function () {

        // Get the btn button of the page

        var btn = document.getElementById("btn");

        // alert(btn);


        // Bind an event to the btn button (click event onclick)

        // Event source: btn button event type: onclick execution instruction: it is the function function of assignment

        btn.onclick = function () {

            alert("congratulations, Five million!");

        }

    }
</script>

</head>
<body>

<button id="btn">Button</button>

</body>

</html>

This is the end of the foundation.

Tags: Javascript

Posted by phillips321 on Sat, 07 May 2022 08:27:23 +0300