JavaScript is the most popular scripting language on the Internet. This language can be used for HTML and web, and can be widely used on servers, PCs, laptops, tablets, smartphones and other devices.
Features of JavaScript
JavaScript has been standardized as a language by ECMA (European Computer Manufacturers Association) through ECMAScript.
Year | Name | Description |
---|---|---|
1997 | ECMAScript 1 | First version |
1998 | ECMAScript 2 | Version changes |
1999 | ECMAScript 3 | Add regular expression Add try/catch |
ECMAScript 4 | is not released. | |
2009 | ECMAScript 5 | adds "strict mode", and strict mode adds JSON support. |
2011 | ECMAScript 5.1 | version changes. |
2015 | ECMAScript 6 | adds classes and modules. |
2016 | ECMAScript 7 | adds exponential operator (**). Add Array.prototype.includes |
Scripts in HTML must be located between the <script> and </script> tags. Scripts can be placed in the <body> and <head> sections of an HTML page.
Often, we need to execute code when an event occurs, such as when the user clicks a button. If we put the JavaScript code into a function, we can call the function when the event occurs.
Example 1: script function in head
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>script in head tag</title> <script> function myFunction() { document.getElementById("demo").innerHTML = "This is my function"; } </script> </head> <body> <h1>My function</h1> <p id="demo">A paragraph</p> <button type="button" onclick="myFunction()">This is a function</button> </body> </html>
Example 2: script function in body
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>script in body</title> </head> <body> <h1>My function</h1> <p id="demo">My function</p> <button type="button" onclick="myFunction()">Click</button> <script> function myFunction() { document.getElementById("demo").innerHTML = "This is my function" } </script> </body> </html>
JavaScript can also be placed externally for calling. Note that the external extension is .js.
Example 3: External call JavaScriptExternal
call.js
function myFunction() { document.getElementById('demo').innerHTML = "This is my function" }
Call external script
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Calling external script</title> </head> <body> <p id="demo">A paragraph of text</p> <button type="button" onclick="myFunction()">Try it</button> <script src="external script.js"></script> </body> </html>
JavaScript Data can be output in different ways:
Example 1: aler() pop-up window output
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>alert output</title> </head> <body> <h1>alert output</h1> <script> window.alert(5 + 6) </script> </body> </html>
Example 2: document.write() output
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>document.write output</title> </head> <body> <h1>document.write output</h1> <script> document.write(Date()); document.write("Hello,Web!"); </script> </body> </html>
Example 3: Write to HTMl document
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Write to HTMl document</title> </head> <body> <h1>Write to HTMl document</h1> <script> function myFunction() { document.write("function output"); } </script> <button onclick="myFunction()">Click here</button> </body> </html>
Example 4: Use console.log() to write to the browser's console
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Use console.log() to write to the browser's console</title> </head> <body> <h1>console.log() writes to the browser’s console</h1> <script> a = 5; b = 6; c = a + b; console.log(c) </script> </body> </html>
JavaScript is a scripting language. It is a lightweight but powerful programming language.
Literals
In programming languages, generally fixed values are called literals.
Note that in JavaScript, the statement needs to be terminated with ";" .JavaScrip
variables
In programming languages, variables are used to store data values. JavaScript uses the keyword var to define variables, and uses the equal sign to assign values to variables. Variables can operate on each other:
var y = false // Boolean value var length = 16; // Number var points = x * 10; // Number calculation var lastName = "Johnson"; // String var cars = ["Saab", "Volvo", "BMW"]; // Array var person = {firstName:"John", lastName:"Doe"}; // Object dictionary
JavaScript function
In order to repeatedly reference the same function and reduce the convenience of code writing and maintenance, JavaScript provides function functions, guided by the keyword function:
function myFunc (a, b) { return a + b; // Return the result of a+b}
JavaScript features
Compared with other languages, JavaScript has the following features:
abstract | else | instanceof | super |
boolean | enum | int | switch |
break | export | interface | synchronized |
byte | extends | let | this |
case | false | long | throw |
catch | final | native | throws |
char | finally | new | transient |
class | float | null | true |
const | for | package | try |
continue | function | private | typeof |
debugger | goto | protected | var |
default | if | public | void |
delete | implements | return | volatile |
do | import | short | while |
double | in | static | with |
JavaScript comment (same as Java)
// This is the code: single sentence comment, usually ctrl + L key in the editor.
/* This is the code*/: Multi-line comments, usually ctrl + shift + L keys in the editor.
JavaScript statements are commands issued to the browser, telling the browser what to do. The following JavaScript statement outputs the text "Hello World!" to the HTML element with id="demo":
document.getElementById("demo").innerHTML = "Hello World!";
Unlike Python, JavaScript code blocks are all in In curly brackets, this is very similar to Java.
Java Identifier
Statement | Description |
---|---|
break | is used to break out of a loop. |
catch | statement block is executed when an error occurs during the execution of the try statement block. |
continue | skips an iteration in the loop. |
do ... while | executes a statement block and continues executing the statement block when the conditional statement is true. |
for | can execute the code block a specified number of times when the conditional statement is true. |
for ... in | is used to traverse the properties of an array or object (loop through the properties of an array or object). |
function | defines a function |
if...else | to perform different actions based on different conditions. |
return | exit function |
switch | is used to perform different actions based on different conditions. |
throw | throws (generates) an error. |
try | implements error handling and is used together with catch. |
var | declares a variable. |
while | When the conditional statement is true, execute the statement block. |
Most languages can automatically complete spaces. We recommend adding spaces on both sides of the operator to make it clear and beautiful. However, you should pay attention to the usage of spaces in HTML and do not mess around. In JavaScript, the following two sentences are the same:
var a = 10; var b=10;
Similar to Python, JavaScript is also a scripting language and is interpreted.
Definition Object
Everything is an object, an abstract instance of characteristics among things with the same characteristics. Like Xiao Ming among humans.
In JavaScript, an object is a container of attribute variables, similar to a dictionary in Python or a hash map in Java, which defines the attributes of the object.
var people = { firstName: "Mike", lastName: "Smith", age: "18", address: "Beijing", job: "Student" };
The above is the object definition. Of course, you can also write it in one line. I do it for the sake of beauty, and I urge everyone to write like this in the future.
To access object properties
we can say "JavaScript objects are containers for variables". However, we usually think of "JavaScript objects as containers of key-value pairs". Key-value pairs are usually written as key : value (key and value are separated by colon). Key-value pairs are usually called object properties in JavaScript objects. We also access properties through the universal "." (most languages use this).
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>This is the website</title> </head> <body> <h1>Access class attributes</h1> <!--The following statement must come before script--> <p id="demo"></p> <script> var people = { firstName: "Mike", lastName: "Smith", age: "18", address: "Beijing", job: "Student" }; document.getElementById("demo").innerHTML = people["firstName"] + "." + people.lastName; </script> </body> </html>
Two access methods, you can use object name.property or object name.["property"].
A function is an event-driven or reusable block of code that executes when it is called. When this function is called, the code within the function is executed. Functions can be called directly when an event occurs (such as when the user clicks a button) and can be called from anywhere by JavaScript.
Parameters and Return Values
When you call a function, you can pass it values, called parameters, and there is no limit to the number of parameters.
function myFunction( var1 , var2 )
{
code
}
When calling parameters, they should be passed in strict accordance with their order, as shown below:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>This is a JavaScript website</title> </head> <body> <h1>Function parameter passing problem</h1> <p>Click the button below to call</p> <button onclick="myFunc('Mike','18','Beijing')">Click here</button> <script> function myFunc(name, age, address) { alert("My name is " + name + ", age is " + age + " and my home is in " + address); } </script> </body> </html>
JavaScript functions are allowed to have return values, and the return keyword is return. When the function returns a value, the function will stop executing, and the statements following return will not be executed.
Example: Calculate the product of two numbers and return the result
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JavaScript website</title> </head> <body> <h1>Calculate the value of two numbers and return</h1> <p id="demo"></p> <script> function myFunc(a, b) { return a * b; } document.getElementById("demo").innerHTML = myFunc(3, 4); </script> </body> </html>
Variables
JavaScript variables are divided into two types:
When we assign a value to an undeclared JavaScript variable, the variable will automatically be treated as a property of window. For example, the following statement:
name = "Mike";
will declare an attribute name of window. Global variables created by assigning values to undeclared variables in non-strict mode are configurable attributes of the global object and can be deleted. For example:
var var1 = 1; // Global properties cannot be configured var2 = 2; // Without var declaration, global properties can be configured console.log(this.var1); // 1 console.log(window.var1); // 1 delete var1; // false cannot delete console.log(var1); //1 delete var2; console.log(delete var2); // true console.log(var2); // Error variable has been deleted. Undefined
description:
HTML events are things that happen on HTML elements. When JavaScript is used in HTML pages, JavaScript can trigger these events.
HTML events can be browser actions or user actions. The following are examples of HTM events:
Normally, when an event occurs, you can do something. JavaScript can execute some code when an event is triggered. Event attributes can be added to HTML elements and JavaScript code can be used to add HTML elements.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JavaScript event</title> </head> <body> <h1>Two ways to handle JavaScript events</h1> <p id="demoOne"></p> <button onclick="getElementById('demoOne').innerHTML=Date()">Click to view time 1</button> <p id="demoTwo"></p> <button onclick="this.innerHTML=Date()">Click to view time 2</button> </body> </html>
JavaScript is usually multi-line code, and the less common one is called through event attributes.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JavaScript event</title> </head> <body> <h1>JavaScript event attribute call</h1> <p>Click to execute the <em>myFunc()</em> function</p> <button onclick="myFunc()">Click here</button> <p id="one"></p> <script> function myFunc() { document.getElementById("one").innerHTML = Date(); } </script> </body> </html>
Event | description |
---|---|
onchange | HTML element changes |
onclick | The user clicks on the HTML element |
onmouseover | The user moves the mouse on an HTML element |
onmouseout | The user moves the mouse away from an HTML element |
onkeydown | The user presses the keyboard key |
onload | The browser has completed the page |
More events will continue to be learned after
loading |
Event role
Events can be used to handle form validation, user input, user behavior and browser actions:
multiple methods can be used to execute JavaScript. Event code:
: A collection of characters.
var a = "abc"; var b = "Hello";
Similar to Python, each character in the string can be accessed using an index:
var c = b[1]; // e
length
This property can calculate the length of the string.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>String length</title> </head> <body> <script> var txtOne = "Hello World!"; document.write("<p>" + txtOne.length + "</p>"); var txtTwo = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; document.write("<p>" + txtTwo.length + "</p>"); </script> </body> </html>
JavaScript also has some special characters. For example, when we want to print quotation marks, we need to add "" to escape, otherwise the compiler cannot parse them.
code | output |
---|---|
' | single quote |
" | double quote |
\ | backslash |
nline | feed |
rcarriage | return |
ttab | (tab character) |
bbackspace | character |
fformfeed character |
string as an object
, usually, JavaScript strings are primitive values and can be created using characters: var firstName = "Mike", but we can also use the new keyword to define a string as an object: var firstName = new String("Mike"), which is similar to Java Similar.
property | description |
---|---|
constructor | returns the function that creates the string property |
length | returns the length of the string |
prototype | allows you to add properties and methods to the object |
method | description |
---|---|
charAt() | returns the character at the specified index position |
charCodeAt() | returns Specify the Unicode value of the character at the index position. |
concat() | concatenates two or more strings and returns the connected string. |
fromCharCode() | converts Unicode into a string. |
indexOf() | returns the position where the specified character appears for the first time in the string. |
lastIndexOf() | returns the position of the last occurrence of the specified character in the string |
localeCompare() | uses a local specific order to compare two strings |
match() | finds a match of one or more regular expressions |
replace() | replaces with a regular expression Matching substring |
search() | retrieves the value that matches the regular expression |
slice() | extracts a fragment of the string and returns the extracted part in a new string |
split() | splits the string into an array of substrings |
substr () | Extract the specified number of characters in the string from the starting index number |
substring () | Extract the characters between the two specified index numbers in the string |
toLocaleLowerCase () | Convert the string to lowercase according to the locale of the host, there are only a few Languages (such as Turkish) have local-specific case mapping |
toLocaleUpperCase() | to convert strings to uppercase according to the locale of the host. Only a few languages (such as Turkish) have local-specific case mapping |
toLowerCase() | to convert strings |
Convert to lowercase | |
toString() | Returns the string object value |
toUpperCase() | Convert the string to uppercase |
trim() | Remove the leading and trailing blanks of the string |
valueOf() | Returns the original value of a string object |
== and === Difference
1. For basic types such as string and number, there is a difference
2. For advanced types such as Array and Object, there is no difference between == and ===
for "pointer address" comparison.
3. There is a difference between basic types and advanced types.
4. != is the non-operation of ==, !== is the non-operation of ===
var num=1; var str="1"; var test=1; test == num //true same type and same value test === num //true same type and same value test !== num //false test has the same type as num, and its value is also the same. The non-operation must be false num == str //true Convert str to a number and check whether it is equal. num != str //false == non-operation num === str //false type is different, return false directly num !== str //true The different types of num and str mean that they are not equal. The non-operation is naturally true.
Operator | description | example | x Operation result | y Operation result |
---|---|---|---|---|
+ | addition | x =y+2 | 7 | 5 |
-Subtraction | x | =y-2 | 3 | 5 |
* | Multiplication | x=y*2 | 10 | 5 |
/ | Division | x=y/2 | 2.5 | 5 |
% | modulo (remainder) | x=y%2 | 1 | 5 |
++ | increment | x=++y | 6 | 6 |
x=y++ | 5 | 6 | ||
--decrement | x= | --y | 4 | 4 |
x=y-- | 5 | 4 |
operator | examples | are equivalent to | operations Result |
---|---|---|---|
= | x=y | x=5 | |
+= | x+=y | x=x+y | x=15 |
-= | x-=y | x=xy | x=5 |
*= | x*=y | x=x*y | x=50 |
/= | x/=y | x= x/y | x=2 |
%= | x%=y | x=x%y | x=0 |
Operator | description | comparison | return value |
---|---|---|---|
== | equal to | x==8 | false |
x==5 | true | ||
= == | Absolutely equal (both value and type are equal) | x==="5" | false |
x===5 | true | ||
!= | not equal to | x!=8 | true |
!== | Not absolutely equal (one of the value and type is not equal, or Both are not equal) | x!=="5" | true |
x!==5 | false | ||
> | greater than | x>8 | false |
< | less than | x<8 | true |
>= | greater than or equal to | x>=8 | false |
<= | less than or equal to | x<= 8 | true |
<= | less than or equal to | x<=8 | true |
operator | description | examples |
---|---|---|
&& | and | (x < 10 && y > 1) is true |
|| | or | (x== 5 || y==5) is false |
! | not | !(x==y) is true |
JavaScript also contains conditional operators that assign values to variables based on certain conditions. For example:
variablename=(condition)?value1:value2
In JavaScript, we can use the following conditional statements:
the if statement
will execute the code only when the condition is true. For example:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv="content-Type" charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <title>JavaScript website</title> </head> <body> <h1>This is an if statement</h1> <button onclick="myFunc()">Click here</button> <p id="one"></p> <script> function myFunc() { var x = ""; var time = new Date().getHours(); if (time < 20) { x = "Hello, Before 20:00"; } document.getElementById("one").innerHTML = x; } </script> </body> </html>
if...else statement
Use the if...else statement to execute code when the condition is true and other code when the condition is false.
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv="content-Type" charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <title>JavaScript website</title> </head> <body> <h1>This is an if...else statement</h1> <button onclick="myFunc()">Click here</button> <p id="one"></p> <script> function myFunc() { var x = ""; var time = new Date().getHours(); if (time < 20) { x = "Hello, Before 20:00"; }else { x = "Hello, After 20:00"; } document.getElementById("one").innerHTML = x; } </script> </body> </html>
Multiple if..else statements
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv="content-Type" charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <title>JavaScript website</title> </head> <body> <h1>Multiple if...else statements</h1> <button onclick="myFunc()">Click here</button> <p id="one"></p> <script> function myFunc() { var x = ""; var time = new Date().getHours(); if (time < 12) { x = "Good morning"; } else if (time < 14) { x = "Good afternoon"; } else { x = "Good afternoon"; } document.getElementById("one").innerHTML = x; } </script> </body> </html>
switch statement
Use the switch statement to select one of multiple blocks of code to be executed. For example:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv="content-Type" charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <title>JavaScript website</title> </head> <body> <h1>switch statement</h1> <button onclick="myFunc()">Click here</button> <p id="one"></p> <script> function myFunc() { var x = ""; var time = new Date().getMonth(); switch (time) { case 0: x = "January"; break; case 1: x = "February"; break; case 2: x = "March"; break; case 3: x = "April"; break; case 4: x = "May"; break; case 5: x = "Jane"; break; case 6: x = "July"; break; case 7: x = "August"; break; case 8: x = "September"; break; case 9: x = "October"; break; case 10: x = "November"; break; case 11: x = "December"; break; default: x = "ERROR"; } document.getElementById("one").innerHTML = x; } </script> </body> </html>
JavaScript supports different types of loops:
for loop
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JavaScript loop</title> </head> <body> <h1>Click the button to loop the code 5 times. </h1> <button onclick="myFunc()">Click here</button> <p id="demo"></p> <script> function myFunc() { var x = ""; for (var i = 0; i < 5; i++) { x = x + "The number is" + i + "<br>"; } document.getElementById("demo").innerHTML = x; } </script> </body> </html>
fo /in loop
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv="content-Type" charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <title>Title</title> </head> <body> <p>Click the button below to traverse the object's person attributes</p> <button onclick="myFunc()">Click here</button> <p id="one"></p> <script> function myFunc() { let x; let text = ""; const person = { firstName: "Bill", lastName: "Gates", age: 56 }; for (x in person) { text = text + " " + person[x]; } document.getElementById("one").innerHTML = text; } </script> </body> </html>
while loop
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv="content-Type" charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <title>Title</title> </head> <body> <p>Click the button and the output will be printed if i is less than 5</p> <button onclick="myFunc()">Click here</button> <p id="one">Show here</p> <script> function myFunc() { let x = "", i = 0; while (i < 5) { x = x + "This number is" + i + "<br>"; i++; } document.getElementById("one").innerHTML = x } </script> </body> </html>
do/while loop
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv="content-Type" charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <title>Title</title> </head> <body> <p>Click the button to print a number less than 5</p> <button onclick="myFunc()">Click here</button> <p id="one"></p> <script> function myFunc() { let x = ""; let i = 0; do { x = x + "The number is" + i + "<br>"; i++; } while (i < 5); document.getElementById("one").innerHTML=x; } </script> </body> </html>
Comparison between for loop and while loop
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv="content-Type" charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <title>Title</title> </head> <body> <p>This is funcOne</p> <button onclick="funcOne()">Click funcOne</button> <p id="one">funcOne is here</p> <p>This is funcTwo</p> <button onclick="funcTwo()">Click funcTwo</button> <p id="two">funcTwo is here</p> <script> function funcOne() { numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]; let i = 0; let addRes = 0; while (numbers[i]) { addRes += numbers[i]; i++; } document.getElementById("one").innerHTML = addRes + "<br>"; } function funcTwo() { numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]; let i = 0; let mulRes = 1; for (; numbers[i];) { mulRes *= numbers[i]; i++; } document.getElementById("two").innerHTML = mulRes + "<br>"; } </script> </body> </html>
Break and Continue
break statements are used to break out of loops. continue is used to skip an iteration in a loop.
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv="content-Type" charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <title>Title</title> </head> <body> <p>This is the continue and break statements</p> <button onclick="funcOne()">Click funcOne</button> <p id="one">This is funcOne</p> <br> <br> <br> <br> <br> <br> <button onclick="funcTwo()">Click funcTwo</button> <p id="two">This is funcTwo</p> <script> function funcOne() { let x = ""; let i = 0; for (i = 0; i < 10; i++) { if (i < 5) { break; } x = x + "The number is" + i + "<br>"; } document.getElementById("one").innerHTML = x; } function funcTwo() { let x = ""; let i = 0; for (i = 0; i < 10; i++) { if (i === 8) { continue; } x = x + "The number is" + i + "<br>"; } document.getElementById("two").innerHTML = x; } </script> </body> </html>
use the typeof operator to detect the data type of the variable.
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv="content-Type" charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <title>Title</title> </head> <body> <p id="one"></p> <script> document.getElementById("one").innerHTML = typeof "john" + "<br>" + typeof 3.14 + "<br>" + typeof false + "<br>" + typeof [1, 2, 3, 4] + "<br>" + typeof {name: 'john', age: 34}; </script> </body> </html>
In JavaScript, an array is a special object type. Therefore typeof [1,2,3,4] returns object.
null means empty, that is, "nothing". When using typeof detection, object is returned. Objects can be cleared using undefined.
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv="content-Type" charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <title>Title</title> </head> <body> <p>one:</p> <p id="one"></p> <p>two:</p> <p id="two"></p> <script> var person = {firstName: "Bill", lastName: "Gates", age: 50}; var person = null; document.getElementById("one").innerHTML = typeof person; person = undefined document.getElementById("two").innerHTML = typeof person; </script> </body> </html>
The constructor property returns the constructor of all JavaScript variables. You can use the constructor property to check whether the object is an array or a date (containing the string "Date"), etc.
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv="content-Type" charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <title>Title</title> </head> <body> <p>The constructor attribute returns a variable or constructor</p> <p id="one">HRER</p> <script> document.getElementById("one").innerHTML = "Hello".constructor + "<br>" + 3.14.constructor + "<br>" + false.constructor + "<br>" + [1, 2, 3].constructor + "<br>" + {name: "Hello", age: 18}.constructor + "<br>" + new Date().constructor + "<br>" + function () { }.constructor; </script> </body> </html>
JavaScript variables can be converted to new variables or other data types:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv="content-Type" charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <title>Title</title> </head> <body> <p>String() method can convert numbers into strings</p> <p id="one">HERE</p> <p>The toString() method can convert numbers into strings</p> <p id="two">HERE</p> <script> let x = 123; document.getElementById("one").innerHTML = String(x) + "<br>" + String(123) + "<br>" + String(100 + 23); document.getElementById("two").innerHTML = x.toString() + "<br>" + (123).toString() + "<br>" + (100 + 123.2).toString(); </script> </body> </html>
Operator+ can be used to convert variables to numbers:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv="content-Type" charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <title>Title</title> </head> <body> <P>The typeof operator returns the variable or expression type</P> <button onclick="myFuncOne()">CLICK HERE ONE</button> <p id="one">HERE</p> <button onclick="myFuncTwo()">CLICK HERE TWO</button> <p id="two">HERE</p> <script> function myFuncOne() { let y = "5"; let x = +y; document.getElementById("one").innerHTML = typeof y + "<br>" + x + "<br>" + typeof x; } function myFuncTwo() { let a = "Hello"; let b = +a; document.getElementById("two").innerHTML = typeof a + "<br>" + b + "<br>" + typeof b; } </script> </body> </html>
primitive value | conversion to number | conversion to string | conversion to Boolean value |
---|---|---|---|
false | 0 | "false" | false |
true | 1 | "true" | true |
0 | 0 | "0" | false |
1 | 1 | "1" | true |
"0" | 0 | "0 " | true |
"000" | 0 | "000" | true |
"1" | 1 | "1" | true |
NaN | NaN | "NaN" | false |
Infinity Infinity | " | Infinity" | true |
-Infinity | -Infinity | "-Infinity" | true |
"" | 0 | "" | false |
"20" | 20 | " 20" | true |
"Runoob" | NaN | "Runoob" | true |
[ ] | 0 | "" | true |
[20] | 20 | "20" | true |
[10,20] | NaN | "10,20" | true |
["Runoob"] | NaN | "Runoob" | true |
["Runoob ","Google"] | NaN | "Runoob,Google" | true |
function(){} | NaN | "function(){}" | true |
{ } | NaN | "[object Object]" | true |
null | 0 | "null" | false |
undefined | NaN | "undefined" | false |
Regular expression (English: Regular Expression, often abbreviated as regex, regexp or RE in code) uses a single string to describe and match a series of string search patterns that comply with a certain syntax rule.
search()
is used to retrieve a specified substring in a string, or retrieve a substring that matches a regular expression, and returns the starting position of the substring.
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv="content-Type" charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <title>Title</title> </head> <body> <p>Retrieve string, match position</p> <button onclick="myFuncOne()">CLICK HERE ONE</button> <p id="one">HERE</p> <button onclick="myFuncTwo()">CLICK HERE TWO</button> <p id="two">HERE</p> <script> function myFuncOne() { let str = "Hello,World!"; document.getElementById("one").innerHTML = str.search(/World/i); } function myFuncTwo() { let str = "Welcome to China!"; document.getElementById("two").innerHTML = str.search("China"); } </script> </body> </html>
replace()
is used to replace some characters with other characters in a string, or replace a substring that matches a regular expression.
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv="content-Type" charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <title>Title</title> </head> <body> <p>Regular expression replace() replacement</p> <button onclick="myFuncOne()">CLICK ONE</button> <p id="one">Hello,Java</p> <button onclick="myFuncTwo()">CLICK TWO</button> <p id="two">Hello,Java</p> <script> function myFuncOne() { let str = document.getElementById("one").innerHTML; document.getElementById("one").innerHTML = str.replace(/Java/i, "Python"); } function myFuncTwo() { let str = document.getElementById("two").innerHTML; document.getElementById("two").innerHTML = str.replace("Java","JavaScipt"); } </script> </body> </html>
Regular expression pattern
modifier | description |
---|---|
i | performs case-insensitive matching. |
g | performs a global match (finds all matches instead of stopping after the first match is found). |
m | performs multi-line matching. |
Expression | Description |
---|---|
[abc] | Finds any character between square brackets. |
[0-9] | finds any number from 0 to 9. |
(x|y) | finds any options separated by |. |
quantifier | description |
---|---|
n+ | matches any string containing at least one n . |
n* | matches any string containing zero or more n 's. |
n? | matches any string containing zero or one n . |
test()
is used to detect whether a string matches a certain pattern. If the string contains matching text, it returns true, otherwise it returns false.
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv="content-Type" charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <title>Title</title> </head> <body> <script> let obj = new RegExp("e"); let boolOne = obj.test("Hello,This is JavaScript"); let boolTwo = obj.test("This is JavaScript"); document.write(boolOne + "<br>" + boolTwo); </script> </body> </html>
exec()
is used to retrieve matches of regular expressions in a string. The function returns an array in which the matching results are stored. If no match is found, the return value is null.
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv="content-Type" charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <title>Title</title> </head> <body> <script> let obj = new RegExp(/e/); resOne = obj.exec("Hello,This is JavaScript"); resTwo = obj.exec("This is JavaScript"); /*No means null*/ document.write(resOne + "<br>" + resTwo); </script> </body> </html>
Error Type
try...catch
The try statement allows us to define a code block that is tested for errors during execution, and the catch statement allows us to define a code block that is executed when an error occurs in the try code block.
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv="content-Type" charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <title>Title</title> </head> <body> <input type = "Button" value = "View message" OnClick = "MyFunc ()"> <script> let txt = "";; Function myfunc () { try { Alert111 ("Hello, World!") } catch (err) { txt = "There is an error here n n"; txt + = "Error description:" + err.message + " n n"; txt += "Click OK to continue n n"; alert (txt) } } </script> </body> </html>
Throw
Throw statement allows us to create custom errors. The correct technical term is: creation or throwing an exception. If Throw and Try and CATCH are used, then you can control the current flow and generate custom error messages.
<!DOCTYPE html> <html lang = "zh-cn"> <head> <meta http-equiv = "content-type" charset = "utf-8"> <meta http-equiv = "x-ua-compatible" content = "ie = edge">> <Title> Title </title> </head> <body> <p> Please enter a number between 5-10 </p> <laabel for = "One"> </Label> <input ID = "One" Type = "Text"> <button type = "Button" Onclick = "MyFunc ()"> Click </Button> <p ID = "Message"> HERE </p> <script> Function myfunc () { Let Message; let x; Message = document.GetelementByid ("Message"); message.innerhtml = ""; x = document.GetelementByid ("One"). Value; try { if (x === "") Throw "Value is empty"; if (isnan (x)) Throw "is not a number"; x = number (x); if (x <5) Throw "too small"; if (x> 10) Throw "too big"; } catch (error) { Message.innerhtml = "Error" + error; } } </script> </body> </html>
the JavaScript function. There are 4 ways to call. The difference in each method is the initialization of this. Generally speaking, in JavaScript, this points to the current object of the function execution.
Call 1: Call theOne
Function MyFunc (a, B) {
as a function call
Return a * b; } MyFunc (1, 2);
Two
Function MyFunc (A, B) {{ Return a * b; } Window.myfunc (1, 2);
Call 2: Function as a method call
<! Doctype html> <html lang = "zh-cn"> <head> <meta http-equiv = "content-type" charset = "utf-8"> <meta http-equiv = "x-ua-compatible" content = "ie = edge">> <Title> Title </title> </head> <body> <p> Function as a method call </p> <p ID = "One"> Here </p> <script> let myObject = { firstName: "Bill", LastName: "Gates", fullName: FUNCTION () { Return this.firtname + "" + this.lastname; } }; document.GetelementByid ("One"). Innerhtml = MyObject.FullName (); </script> </body> </html>
Call 3: Use the constructor to call the function
<! Doctype html> <html lang = "zh-cn"> <head> <meta http-equiv = "content-type" charset = "utf-8"> <meta http-equiv = "x-ua-compatible" content = "ie = edge">> <Title> Title </title> </head> <body> <p> In this instance, myfunc () is the constructor of the function </p> <p ID = "One"> </p> <script> Function MyFunc (ARGONE, ARGTWO) { this.Name = Argone; this.number = argtwo; } Let x = new myfunc ("Hello", 123); document.GetelementByid ("One"). Innerhtml = x.name; </script> </body> </html>
Call 4: As a function method to mobilize the function
<! Doctype html> <html lang = "zh-cn"> <head> <meta http-equiv = "content-type" charset = "utf-8"> <meta http-equiv = "x-ua-compatible" content = "ie = edge">> <Title> Title </title> </head> <body> <p> As a function method to mobilize the function </p> <p ID = "One"> Here </p> <script> Let Obj, Array; function myfunc (a, b) {{ Return a * b; } array = [5, 6]; obj = myfunc.apply (obj, array); document.GetelementByid ("One"). Innerhtml = obj; </script> </body> </html>The
internal function
is actually in JavaScript, all functions can access the scope of the previous layer. JavaScript supports the nested function, and the nested function can access the function variable of the previous layer. The embedded function plus () can access the Counter variable of the parent function:
<! Doctype html> <html lang = "zh-cn"> <head> <meta http-equiv = "content-type" charset = "utf-8"> <meta http-equiv = "x-ua-compatible" content = "ie = edge">> <Title> Title </title> </head> <body> <p> Embedded Function </p> <p ID = "One"> Here </p> <script> document.GetelementByid ("One"). Innerhtml = add (); function add() { Let counter = 0; Function plus () { counter += 1; } plus (); Return Countr; } </script> </body> </html>The self -call of the
closing
function is called Bibao
<! Doctype html> <html lang = "zh-cn"> <head> <meta http-equiv = "content-type" charset = "utf-8"> <meta http-equiv = "x-ua-compatible" content = "ie = edge">> <Title> Title </title> </head> <body> <p> Local counter </p> <button type = "Button" Onclick = "MyFunc ()"> counter </Button> <p ID = "One"> Here </p> <script> let add = (function () { Let counter = 0; Return function () { Return counter += 1; } })(); Function myfunc () { document.GetelementByid ("One"). Innerhtml = add (); } </script> </body> </html>