Basic knowledge of JavaScript 11 ~ 15

Posted by spectacell on Sat, 18 Sep 2021 05:39:30 +0200

11. JavaScript functions
JavaScript functions are blocks of code designed to perform specific tasks.

JavaScript functions are executed when code calls it.

example

function myFunction(p1, p2) {
    return p1 * p2;              // This function returns the product of p1 and p2
}

Try it yourself
JavaScript function syntax
JavaScript functions are defined by the function keyword, followed by the function name and parentheses ().

Function names can contain letters, numbers, underscores, and dollar signs (the same rules as variable names).

Parentheses can include comma separated parameters:

(parameter 1, parameter 2,...)
The code executed by the function is placed in curly braces: {}

Function name (parameter 1, parameter 2, parameter 3){
Code to execute
}
Function parameters are the names listed in the function definition.

Function arguments are the real values received by the function when the function is called.

In a function, parameters are local variables.

In other programming languages, a function approximates a Procedure or Subroutine.

function call
The code in the function will execute when the function is called by other code:

When an event occurs (when the user clicks the button)
When JavaScript code calls
Automatic (self calling)
You will learn more about function calls in this tutorial.

Function return
When JavaScript reaches the return statement, the function stops executing.

If a function is called by a statement, JavaScript will "return" to execute code after the statement is called.

Function usually calculates the return value. This return value will be returned to the caller:

example

Calculates the product of two numbers and returns the result:

var x = myFunction(7, 8);        // Call the function, and the return value is assigned to x

function myFunction(a, b) {
    return a * b;                // Function returns the product of a and b
}
x The result will be:

56

Try it yourself
Why use functions?
You can reuse code: you can use it multiple times as long as you define it once.

You can pass different parameters to the same function multiple times to produce different results.

example
Convert Fahrenheit to Celsius:

function toCelsius(fahrenheit) {
    return (5/9) * (fahrenheit-32);
}

document.getElementById("demo").innerHTML = toCelsius(77);

Try it yourself
() operator call function
Using the above example, toCelsius refers to the function object, while toCelsius() refers to the function result.

example
Accessing a function without () will return the function definition:

function toCelsius(fahrenheit) {
    return (5/9) * (fahrenheit-32);
}

document.getElementById("demo").innerHTML = toCelsius;

Try it yourself
Functions used as variable values
Functions are used in the same way as variables in all types of formulas, assignments and calculations.

example
Use variables to store the value of a function:

var x = toCelsius(77);
var text = "The temperature is " + x + " Celsius";
You can use functions directly as variable values:

var text = "The temperature is " + toCelsius(77) + " Celsius";

Try it yourself
You will learn more about functions in this tutorial.

local variable
Variables declared in JavaScript functions become local variables of functions.

Local variables can only be accessed within functions.

example

// carName cannot be used in code here

function myFunction() {
    var carName = "Volvo";
    // code here CAN use carName
}

// The code here can use carName

Try it yourself
Since local variables can only be recognized by their functions, variables with the same name can be used in different functions.

Local variables are created at the beginning of the function and deleted when the function completes.
12. JavaScript object
Objects, attributes and methods in real life
In real life, the car is an object.

Cars have attributes such as weight and color, as well as methods such as starting and stopping:
All cars have the same attribute, but the attribute value varies from car to car.

All cars have the same method, but the method will be executed at different times.

JavaScript object
As you have learned before, JavaScript variables are containers for data values.

This code assigns a single value (porsche) to a variable named car:

var car = "porsche";

Try it yourself
Objects are also variables. But objects contain many values.

This code assigns multiple values (porsche, 911, white) to the variable named car:

var car = {type:"porsche", model:"911", color:"white"};

Try it yourself
Values are written as name: value pairs (names and values are separated by colons).

JavaScript objects are containers of named values.

Object properties
Name: value pairs (in JavaScript objects) are called properties.

var person = {firstName:"Bill", lastName:"Gates", age:62, eyeColor:"blue"};

Object method
Objects can also have methods.

Methods are actions performed on objects.

Methods are stored in properties as function definitions.

Methods are functions stored as attributes.

example

var person = {
  firstName: "Bill",
  lastName : "Gates",
  id       : 678,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};

this keyword
In the function definition, this refers to the "owner" of the function.

In the above example, this refers to the person object that "owns" the fullName function.

In other words, this.firstName means the firstName attribute of this object.

Please learn more about this keyword in JS this keyword chapter.

Object definition
We defined (created) a JavaScript object:

example
var person = {firstName:"Bill", lastName:"Gates", age:62, eyeColor:"blue"};
Try it yourself
Spaces and line breaks are allowed. Object definitions can span multiple lines:

example

var person = {
    firstName:"Bill",
    lastName:"Gates",
    age:50,
    eyeColor:"blue"
};

Try it yourself
Access object properties
You can access properties in two ways:

objectName.propertyName
perhaps

objectName["propertyName"]
Example 1
person.lastName;
Try it yourself
Example 2
person["lastName"];
Try it yourself
Access object method
You can access object methods through the following syntax:

objectName.methodName()
example
name = person.fullName();
Try it yourself
If you do not use () to access the fullName method, the function definition is returned:

example
name = person.fullName;
Try it yourself
Methods are actually function definitions stored in the form of attribute values.
Please do not declare strings, numeric values and Boolean values as objects!
If you declare a JavaScript variable with the keyword "new", the variable will be created as an object:

var x = new String(); / / declare x as a String object
var y = new Number(); / / declare y as a Number object
var z = new Boolean(); / / declare Z as a Boolean object
Avoid strings, numeric values, or logical objects. They increase code complexity and slow execution.

You will learn more about objects later in this tutorial.
13. JavaScript events
HTML events are "things" that happen on HTML elements.

When JavaScript is used in HTML pages, JavaScript can "cope" with these events.
HTML events
HTML events can be something that a browser or user does.

Here are some examples of HTML events:

HTML page finished loading
HTML input field modified
HTML button clicked
Usually, when an event occurs, the user wants to do something.

JavaScript allows you to execute code when an event is detected.

With JavaScript code, HTML allows you to add event handlers to HTML elements.

Use single quotation marks:

<element event='some JavaScript'>

Use double quotation marks:

<element event="some JavaScript">

In the following example, the onclick attribute (and code) is added to the < button > element:

example

<button οnclick='document.getElementById("demo").innerHTML=Date()'>What's the time now?</button>

Try it yourself
In the above example, the JavaScript code changes the content of the element with id = "demo".

In the following example, the code (using this.innerHTML) changes the content of its own element:

example

<button οnclick="this.innerHTML=Date()">What's the time now?</button>

Try it yourself
JavaScript code usually has many lines. Event attribute calls are more common:

example

<button οnclick="displayDate()">What's the time now?</button>

Try it yourself
Common HTML events
Here are some common HTML events:

What can JavaScript do?
Event handlers can be used to process and validate user input, user actions, and browser actions:

What should be done whenever the page loads
What to do when the page is closed
The action that should be performed when the user clicks a button
What should be verified when the user enters data
wait
There are many different ways for JavaScript to handle events:

HTML event attribute executable JavaScript code
HTML event attributes can call JavaScript functions
You can assign your own event handlers to HTML elements
You can prevent events from being sent or processed
wait
You will learn more about events and event handlers in the HTML DOM chapter.
14. JavaScript string
JavaScript strings are used to store and manipulate text.

JavaScript string
A JavaScript string is zero or more characters in quotation marks.

example

var x = "Bill Gates"

Try it yourself
You can use single or double quotation marks:

example

var carname = "Porsche 911";
var carname = 'Porsche 911';

Try it yourself
You can use quotation marks in a string as long as they do not match the quotation marks surrounding the string:

example

var answer = "It's good to see you again!";
var answer = "He is called 'Bill'";
var answer = 'He is called "Bill"';

Try it yourself
String length
The built-in property length returns the length of the string:

example

var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;

Try it yourself
Special characters
Because the string must be enclosed by quotation marks, JavaScript misunderstands the string:

var y = "China is the hometown of porcelain, so China has the same name as" China "
The string will be cut as "china is the hometown of porcelain, so china and".

The solution to avoid this problem is to use the \ escape character.

Backslash escape character converts a special character to a string character:

example
Sequence "insert double quotes in string:

example

var x = "China is the hometown of porcelain, so china And\"China(China)\"Same name."

Try it yourself
Sequence 'insert single quotation marks in the string:

example

var x = 'It\'s good to see you again';

Try it yourself
Sequences \: inserting backslashes into strings:

example

var x = "character \\ It's called a backslash.";

Try it yourself
The escape character (\) can also be used to insert other special characters into a string.

Valid escape sequences in the other six JavaScript:

These six escape characters were originally designed to control typewriters, teletypewriters and fax machines. They have no meaning in HTML.

Wrap long lines
For best readability, programmers usually avoid more than 80 strings per line of code.

If a JavaScript statement is not suitable for a whole line, the best line feed position is after an operator:

example

document.getElementById("demo").innerHTML =
"Hello Kitty.";

Try it yourself
You can also wrap a line in a string by a backslash:

example

document.getElementById("demo").innerHTML = "Hello \
Kitty!";

Try it yourself
\Method is not ECMAScript (JavaScript) standard.

Some browsers also do not allow spaces after the \ character.

The safest way to wrap a long string (but a little slow) is to use string addition:

example

document.getElementById("demo").innerHTML = "Hello" + 
"Kitty!";

Try it yourself
You cannot wrap a line of code with a backslash:

example

document.getElementById("demo").innerHTML = \ 
"Hello Kitty!";

Try it yourself
A string can be an object
Typically, JavaScript strings are raw values, created literally:

var firstName = "Bill"
However, the string can also be defined as an object through the keyword new:

var firstName = new String("Bill")
example

var x = "Bill";
var y = new String("Bill");

// typeof x will return a string
// typeof y will return object

Try it yourself
Please do not create a string as an object. It will slow down execution.

The new keyword complicates the code. It may also produce some unexpected results:

When the = = equality operator is used, the equality strings are equal:

example

var x = "Bill";             
var y = new String("Bill");

// (x == y) is true because the values of X and y are equal

Try it yourself
When using the = = = operator, equal strings are not equal because the = = = operator requires both types and values to be equal.

example

var x = "Bill";             
var y = new String("Bill");

// (x === y) is false because X and y are of different types (string and object)

Try it yourself
Even worse. Objects cannot be compared:

example

var x = new String("Bill");             
var y = new String("Bill");

// (x == y) is false because X and y are different objects

Try it yourself
example

var x = new String("Bill");             
var y = new String("Bill");

// (x === y) is false because X and y are different objects

Try it yourself
Note the difference between (xy) and (x=y).

JavaScript objects cannot be compared. Comparing two JavaScript objects will always return false.

15. JavaScript string method
The string method helps you process strings.

String methods and properties
Original values, such as "Bill Gates", cannot have properties and methods (because they are not objects).

However, with JavaScript, methods and properties can also be used for original values, because JavaScript treats the original values as objects when executing methods and properties.

String length
The length property returns the length of the string:

example

var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
Find a string in a string
indexOf() Method returns the index (position) of the first occurrence of the specified text in the string:

example
var str = "The full name of China is the People's Republic of China.";
var pos = str.indexOf("China");

Try it yourself
JavaScript calculates the position from zero.

0 is the first position in the string, 1 is the second, 2 is the third

The lastIndexOf() method returns the index of the last occurrence of the specified text in the string:

example

var str = "The full name of China is the People's Republic of China.";
var pos = str.lastIndexOf("China");

Try it yourself
If no text is found, indexOf() and lastIndexOf() both return - 1.

example

var str = "The full name of China is the People's Republic of China.";
var pos = str.indexOf("USA");

Try it yourself
Both methods accept the second parameter as the starting position for retrieval.

example

var str = "The full name of China is the People's Republic of China.";
var pos = str.indexOf("China", 18);

Try it yourself
The lastIndexOf() method retrieves backward (from end to end), which means that if the second parameter is 50, the retrieval starts from position 50 to the beginning of the string.

example

var str = "The full name of China is the People's Republic of China.";
var pos = str.lastIndexOf("China", 50);

Try it yourself
Retrieves a string from a string
The search() method searches for a string of a specific value and returns the matching location:

example

var str = "The full name of China is the People's Republic of China.";
var pos = str.search("locate");

Try it yourself
Have you noticed?
The two methods, indexOf() and search(), are equal.

The two methods are not equal. The difference is:

The search() method cannot set the second start position parameter.
The indexOf() method cannot set a more powerful search value (regular expression).
You will learn about these more powerful retrieval values in the regular expressions section.

Extract partial string
There are three ways to extract partial strings:

slice(start, end)
substring(start, end)
substr(start, length)
slice() method
slice() extracts a part of the string and returns the extracted part in the new string.

This method sets two parameters: start index (start position) and end index (end position).

This example cuts the segment from position 7 to position 13 in the string:

example

var str = "Apple, Banana, Mango";
var res = str.slice(7,13);


res The results are:

Banana

Try it yourself
If a parameter is negative, the count starts at the end of the string.

This example cuts the segment from position - 12 to position - 6 in the string:

example

var str = "Apple, Banana, Mango";
var res = str.slice(-13,-7);
res The results are:

Banana

Try it yourself
If the second parameter is omitted, the method will crop the rest of the string:

example

var res = str.slice(7);

Try it yourself
Or count from the end:

example

var res = str.slice(-13);

Try it yourself
Tip: negative values do not apply to Internet Explorer 8 and earlier.

substring() method
substring() is similar to slice().

The difference is that substring() cannot accept negative indexes.

example

var str = "Apple, Banana, Mango";
var res = str.substring(7,13);
res The results are:

Banana

Try it yourself
If the second parameter is omitted, the substring() will crop the rest of the string.

substr() method
substr() is similar to slice().

The difference is that the second parameter specifies the length of the extracted part.

example

var str = "Apple, Banana, Mango";
var res = str.substr(7,6);
res The results are:

Banana

Try it yourself
If the second parameter is omitted, the substr() will crop the rest of the string.

example

var str = "Apple, Banana, Mango";
var res = str.substr(7);

Try it yourself
The result of res is:

Banana, Mango
If the first argument is negative, the position is calculated from the end of the string.

example

var str = "Apple, Banana, Mango";
var res = str.substr(-5);

Try it yourself
The result of res is:

Mango
The second parameter cannot be negative because it defines length.

Replace string contents
The replace() method replaces the value specified in the string with another value:

example

str = "Please visit Microsoft!";
var n = str.replace("Microsoft", "W3School");

Try it yourself
The replace() method does not change the string that calls it. It returns a new string.

By default, replace() replaces only the first match:

example

str = "Please visit Microsoft and Microsoft!";
var n = str.replace("Microsoft", "W3School");

Try it yourself
By default, replace() is case sensitive. Therefore, MICROSOFT is not matched:

example

str = "Please visit Microsoft!";
var n = str.replace("MICROSOFT", "W3School");

Try it yourself
To perform a case insensitive substitution, use the regular expression / i (case insensitive):

example

str = "Please visit Microsoft!";
var n = str.replace(/MICROSOFT/i, "W3School");

Try it yourself
Note that regular expressions are not quoted.

To replace all matches, use the g flag of the regular expression (for global search):

example

str = "Please visit Microsoft and Microsoft!";
var n = str.replace(/Microsoft/g, "W3School");

Try it yourself
You will learn more about regular expressions in the JavaScript regular expressions chapter.

Convert to uppercase and lowercase
Convert the string to uppercase by toUpperCase():

example

var text1 = "Hello World!";       // character string
var text2 = text1.toUpperCase();  // text2 is text1 converted to uppercase

Try it yourself
Convert the string to lowercase by toLowerCase():

example

var text1 = "Hello World!";       // character string
var text2 = text1.toLowerCase();  // text2 is text1 converted to lowercase

Try it yourself
concat() method
concat() connects two or more strings:

example

var text1 = "Hello";
var text2 = "World";
text3 = text1.concat(" ",text2);

Try it yourself
The concat() method can be used instead of the addition operator. The following two lines are equivalent:

example

var text = "Hello" + " " + "World!";
var text = "Hello".concat(" ","World!");
All string methods return a new string. They do not modify the original string.

Formally: strings are immutable: strings cannot be changed, they can only be replaced.

String.trim()
trim() Method to remove whitespace at both ends of a string:

example
var str = "       Hello World!        ";
alert(str.trim());
Warning: Internet Explorer 8 Or earlier versions are not supported trim() method.

Try it yourself
To support IE 8, you can use the replace() method with regular expressions instead:

example

var str = "       Hello World!        ";
alert(str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''));

Try it yourself
You can also use the replace scheme above to add the trim function to JavaScript String.prototype:

example

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
var str = "       Hello World!        ";
alert(str.trim());

Try it yourself
Extract string characters
These are two safe ways to extract string characters:

charAt(position)
charCodeAt(position)
charAt() method
The charAt() method returns the string with the specified subscript (position) in the string:

example

var str = "HELLO WORLD";
str.charAt(0);            // Return to H

Try it yourself
charCodeAt() method
The charCodeAt() method returns the character unicode encoding of the specified index in the string:

example

var str = "HELLO WORLD";

str.charCodeAt(0);         // Return 72

Try it yourself
Property Access
ECMAScript 5 (2009) allows attribute access to strings []:

example

var str = "HELLO WORLD";
str[0];                   // Return to H

Try it yourself
Using attribute access is a little unreliable:

Not available with Internet Explorer 7 or earlier
It makes the string look like an array (it's not)
If no character is found, [] returns undefined and charAt() returns an empty string.
It is read-only. str[0] = "A" will not generate errors (but it will not work!)
example

var str = "HELLO WORLD";
str[0] = "A";             // No errors are generated, but they do not work
str[0];                   // Return to H

Try it yourself
Tip: if you want to process a string as an array, you can convert it to an array first.

Convert string to array
You can convert strings to arrays through split():

example

var txt = "a,b,c,d,e";   // character string
txt.split(",");          // Separated by commas
txt.split(" ");          // Separated by spaces
txt.split("|");          // Separated by vertical lines

Try it yourself
If the delimiter is omitted, the returned array will contain the entire string in index [0].

If the delimiter is' ', the returned array will be an array separated by a single character:

example

var txt = "Hello";       // character string
txt.split("");           // Separate into characters

Topics: Javascript