Introduction to JavaScript·Speedboard

         In order to use JavaScript in a browser, the HTML page loaded by the browser must contain JavaScript code. There are several ways to insert JavaScript code. We can:

  1. Insert JavaScript in the HTML header.
  2. Insert JavaScript into the body of the HTML (usually at the bottom).
  3. Contains JavaScript files from the same website as the HTML page
  4. Includes JavaScript files from other websites.

        The choice between HTML header and body is a timing issue. If you insert code in the HTML header, it can be used when displaying the HTML body. However, compiling JavaScript code takes time, so sometimes to improve Web responsiveness, JavaScript code is placed at the bottom of the HTML body. If you place it at the bottom of the body, the browser can display the page while the JavaScript code is loaded and compiled. Ideally, the code used when displaying the page is in the header, while the code used afterward can be placed at the bottom of the body of the page.

        When JavaScript becomes heavy, it's good programming practice to put code in separate files. It also allows code reuse, where many pages can load the same JavaScript file. It is also common for provided JavaScript files (such as various frameworks) to be hosted on the maintainer's website or on a public mirror site, so that the code can be updated (bug fixes) without requiring users to modify their web pages.

        In both cases, there are performance benefits because the browser can cache the individual files so they don't have to be reloaded from the remote website for every web page that uses them.

        A function contains a block of code, subprogram, or subroutine that is not called until called. There are many built-in functions in Javascript, as well as the possibility to create user-defined functions.

        Similar to PHP, JavaScript provides the ability to define and use functions as a means of packaging JavaScript code so that it can be used in different places. By using the function name in a statement, you can execute the function's code. Additionally, you can pass parameters to a function to modify its behavior. The function can also return the value to be used wherever it is called.

        Other functions and event handlers can call functions, such as when a page is loaded or when the user generates an event by interacting with the page. You can pass optional parameters or an event object generated by the page element calling the function.

        There are certain rules that you must follow while writing functions, as follows:

  1. All functions begin with the function keyword (a word with a special meaning in JavaScript)
  2. After the function keyword we provide the name of the function
  3. The function name is followed by a set of parentheses ().
  4. Finally, write the block of code to be executed when the function is called within curly braces {}

        Compared to PHP and other programming languages, the JavaScript programming language provides a very flexible way of declaring and using functions. JavaScript functions can be declared in the following ways:

function function-name (arg1, arg2, ...) 
{
      statements; 
}

var x = function (arg1, arg2, ...) { statements; };
var x = new Function(arg1, arg2..., "Function Body");

        So, an example of a simple function that prints a simple "hello" message is:

function hello() 
{ 
      document.write("hello<br>"); 
}

var hello = function () { document.write("hello<br>"); }

        The format of the declaration is the same as before using <script> tags to enclose the JavaScript declaration. So the complete HTML file that defines and calls the above function looks like this:

<!DOCTYPE html> <html lang=”en”>
<head> <meta charset=”utf8”>
<title> The Javascript Functional Hello</title>
<script language="javascript"> <!— function hello() { document.write("hello<br>"); } // --> </script> 
</head> 
<body> 
<script language="javascript"> <!-- hello(); // -->
</script>
</body>
</htm

        The last attribute of the function is the optional return value. This is accomplished by placing a return statement in the function body. The format of the return statement is:

return value;

        When a return statement is encountered, the function terminates immediately and returns the value to the location where the function was called. To demonstrate this, you can define a function that returns the difference between two numbers, like this:

function diff(x, y) 
{ 
          var d = x-y;
          if (d < 0) 
              return y-x; 
          else 
              return d; 
}
        The function above takes two parameters: x and y, and returns the positive difference between the two numbers.
        JavaScript does not check that the number of arguments in the formal definition matches the number of arguments in the actual function call. Any extra arguments in the function call will be ignored, and any extra arguments in the formal definition (too few in the actual call) will be assigned an undefined value.
        When a function is called, it should return something useful (e.g., a value or a string), or it should return a Boolean value (i.e., true or false) to indicate whether the function's result was successful.

named function

        There are two restrictions on function names in JavaScript:
  1. Function names can only contain letters, numbers, or symbols and .$_
  2. The first character cannot be a number.
        Therefore, the following are all valid variable names and will not produce an error:
function calculate_age()
function _name_()
function a$56enn ()

        The following names are not valid and will generate an error:

function sayHi@()
function 1name()

JavaScript variables

        In JavaScript, variables are implicitly and weakly typed, which means they do not require declaration or type casting (data type conversion). Whenever you declare a new variable or constant, JavaScript determines its data type. However, it is recommended to declare variables and initialize them before using them.
        When declaring a JavaScript variable, we can use the keywords  var , let  and  constant .
was Create new global variables (no scope restrictions in the code).
let Creates new local variable (scope only exists in current code block).
constant Create global constants that cannot be changed (no scope restrictions in the code).

        Syntax for declaring and initializing variables:

var myInteger = 10;
var myString = “Hello World!”;或
var myArray = new Array();
let name = “John”
const pi = 3.14

Variables can store different data types. Some common ones include:

Strings A group of characters written in quotation marks, such as "John Doe".
Numbers Numbers can be given with or without decimals. If the number is large or small, it can be written in scientific (exponential) notation
Booleans means true or false
Arrays A group of elements represented by square brackets, where values ​​are separated by commas. Array indexing starts at zero, so the first item is [0], the second is [1], and so on.
Objects A collection of key-value pairs is called an object. Each key-value pair is an attribute.
Undefined If a variable is not assigned a value, its value is undefined

        Please refer to the following code:

let age = 20;
let firstName = 'John';
let lastName = "Doe";
let isStudent = true;
  • In the first line, we declare a variable assigned a number
  • On the second and third lines, we declare variables that have strings assigned to them. Note how quotes of either type are used when assigning string values ​​(i.e. '' and "").
  • On line 4, we declare a variable that stores a boolean value .

        As seen before, another common use of variables is to store HTML objects, like this:

let paragraph = document.getElementById("test");

Change variable value

After a variable is declared, its value can be changed. Consider the following code:

let age = 20;
alert(age);
age = 30;
alert(age);

        First declare the variable age and assign it the value 20 and then display it in the alert. However, the value 30 is then assigned to the variable age. This means that the value 20 has been removed from the memory space created when we declared the variable and replaced with the value 30.

        However, it is important to note that the following code will cause an error:

let age = 20;
alert(age);
let age = 30;
alert(age);

        The problem with the above code is that the variable is redeclared on the third line  age. In JavaScript,  let variables declared using keywords have block-level scope. This means that the same variable name cannot be declared repeatedly in the same scope. So the redeclaration on the third line  age is not legal. If you want to modify the value of a variable, you should  age assign it directly without  let declaring it again.

Named variables

        The same rules learned when discussing named functions also apply to named variables, as follows:
  1. Variable names can only contain letters, numbers, or symbols.$_
  2. The first character cannot be a number.
        Therefore, the following are all valid variable names and will not produce an error:
let persons_age = 20;            
let _name_ = "John"
let a$56enn = false;

        The following names are not valid and will generate an error:

let name@ = "John";
let 9name = "John";

        The first name contains illegal characters and the second name starts with a number.

        Note: Just like functions, variables should always be named with descriptive names,  camelCase will be used when the name contains multiple words . This is where the words come one after another, and each word starts with a capital letter except the first one, like someVariableName. Just because a variable name doesn't cause an error doesn't mean it's a good name!

        JavaScript supports the following types of operators.

  • arithmetic operators
  • comparison operator
  • Logical (or relational) operator
  • assignment operator
  • Conditional (or ternary) operator

        These are similar to other languages, but differ due to the dynamically typed nature of variables in the language.

        As you can see above, assignment operator '=' is used to place a value in a variable. In typed languages, there is a type check to see if the variable on the right is the correct type of the variable. There is no type checking in JavaScript, instead variables are adjusted according to whatever type they are assigned. The following three statements demonstrate how variables ignore types. The syntax of if-else-if statement is as follows −

  var x; // new variable are assigned value ‘undefined’
  x = 23; // x now has a integer value
  x = ’hello world’;// x now has a string value

        The equality operator also has some new properties in JavaScript. The "==" operator compares values ​​after converting types, and the "===" operator performs a strict comparison without type conversion, e.g.

  5 =='5' // returns true
  5 === '5' // returns false

        Inequality operator '! =' and '! ==' behaves the same way.

        There are two operators that test the type of an expression. These are useful because it is not uncommon for us to want to check a variable or parameter of a function that contains a reasonable value, for example a numeric function might want to check whether it has a numeric parameter.

typeof x // returns the type of the value in x as a string

        After looking at JavaScript value types, you'll look at types and instances of operators.

Manipulate strings and numbers

        Strings and numbers are represented in a manner similar to what you would use in C# or Java. However, JavaScript also provides a set of properties for the strings you create. One of the less clear aspects of JavaScript is the difference between string types and string objects. The mapping between the two is not clear, but each string can be viewed as an object, each with associated properties.

        For example, suppose there is a statement:

  var name = "Reza";

        Properties can be accessed from this string. For example:

  name.length – returns the length of the string
  name.indexOf("rr") – returns the index of the string “rr” (0 is first position)

        In addition, there are many member functions for manipulating strings.

        Numbers also have a set of properties that map to primitive numeric values. For example, assume you have the following numeric variables:

var age = 21;

        Property age.toString() Converts a number to a string value. It is automatically called when an operator requires a string value, such as in an expression:

"my age is "+age

JavaScript conditional statements

        JavaScript supports conditional statements of the following form:

  • if statement
  • switch case statement
  • When while, and
  • for for

        The syntax of if-else-if statement is as follows −

if (expression 1) {
   Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
   Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
   Statement(s) to be executed if expression 3 is true
} else {
   Statement(s) to be executed if no expression is true
}

        The syntax of switch case statement is as follows −

switch (expression) {
   case condition 1: statement(s)
   break;
   
   case condition 2: statement(s)
   break;
   ...
   
   case condition n: statement(s)
   break;
   
   default: statement(s)
}

        The syntax of while statement is as follows -

while (expression) {
   Statement(s) to be executed if expression is true
}

        The syntax of For statement is as follows −

for (initialization; test condition; iteration statement) {
   Statement(s) to be executed if test condition is true
}

JavaScript array

        JavaScript arrays are very similar to arrays you use in other programming languages. The key difference is that arrays in JavaScript are not fixed sizes, as you probably remember them. Arrays in JavaScript have dynamic length and expand freely as you assign more values ​​to them. The second difference is that arrays do not necessarily contain values ​​of the same type.

        Actually, you can think of an array as a special type of object where the elements consist of numbers 0, 1, 2, ... instead of strings. Remember that we can access elements in objects like arrays.

        Arrays are more similar to objects in that they have properties and methods. For example, assume we have the following array declaration.

var colours = ["red", "green", "blue"];

        The length of the array can be found as the length attribute:

colours.length

        Arrays can be sorted using the sort function:

 colours.sort();

JavaScript debugging

The console.log() method         can be called   to display errors without stopping code execution.

        When debugging, there may be times when you need to stop the execution of your code.  You can do this by calling  the alert() function.

        Here is a set of examples:

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>

<script>
a = 5;
b = 6;
c = a + b;
console.log(c);
</script>

</body>
</html>

Error handling (exception)

        JavaScript also implements exception handling, but it's called error handling in the documentation. You will be familiar with exceptions in other modern languages ​​such as C# or Java. JavaScript uses a very similar mechanism.

        The main statement is the try-catch structure, which is very similar to the same statement in C# and Java. The general format is:

  try {
       // lots of statements
  }
  catch (err) {
               // error processing code
  }
  finally { // optional
           // code that is always executed (whether error or not)
  }

        JavaScript also allows you to throw your own errors, handled by catch statements, e.g.

  try {
      // lots of statements
         throw 234;
      // lots of statements
         throw "oops error";
      // more statements
  }
  catch (err) {
     // error processing code
  }
 

        Note that in this example, the way the error is raised can be of any type, in this example numbers and strings are raised as error values.

Guess you like

Origin blog.csdn.net/qq_54813250/article/details/132846494