Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the use of JavaScript in the front end of web

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Editor to share with you what is the use of web front-end JavaScript, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

1. Introduction of JavaScript

1. A complete JavaScript implementation consists of the following three different parts:

(1) Core (ECMAScript)

(2) document object Model (DOM) Document object model (Integrated js,css,html)

(3) browser object Model (BOM) Broswer object model (integrating js and browser)

2. Characteristics

JavaScript is a scripting language

JavaScript is a lightweight programming language.

JavaScript is programming code that can be inserted into a HTML page.

After JavaScript is inserted into the HTML page, it can be executed by all modern browsers.

JavaScript is easy to learn.

II. The introduction mode and specification of JavaScript

1. Introduction mode

(1) write code inside the Script tag

/ / write the JS code here

(2) introduce additional JS files

2. Norms

/ / single-line comments

/ *

This is a multiline comment.

, /

Statements in JavaScript should end with a semicolon (;)

3. Variable declaration

(1) the variable name of JavaScript can be composed of _, numbers, letters, and $, and cannot start with a number.

(2) declare variables in the format of var variable name;

Var name = "Myname"; var age = 18

Note:

Variable names are case sensitive.

Hump naming rules are recommended.

Reserved words cannot be used as variable names.

(3) reserved words

Abstract boolean byte

Char class const

Debugger double enum

Export extends final

Float goto implements

Import int interface

Long native package

Private protected public

Short static super

Synchronized throws transient

Volatile

(4)

Alert ("hello"); / / display hello in the pop-up window

Console.log (123); / / use F12 to view the content of Console is 123, and use typeof to view the data type as "number" in Console.

3. JavaScript data type

1. JavaScript has dynamic types

Var x; / / where x is undefinedvar x = 1; / / where x is the number var x = "Ele"; / / where x is a string

2. Numeric type

JavaScript does not distinguish between integer and floating-point types, so there is only one numeric type.

There is also a NaN that means it is not a number (Not a Number).

Common methods:

ParseInt ("123") / / returns 123parseInt (" ABC ") / / returns that the NaN,NaN attribute is a special value that represents a non-numeric value. This property is used to indicate that a value is not a number. ParseFloat ("123.456") / / returns 123.456

3. String

Var a = "Hello"; var b = "world"; var c = a + bscape console.log (c); / / use F12 to view the content of Console is Helloworld

(1) Common methods:

.length returns the length

.trim () remove whitespace

.trimLeft () removes white space on the left

.trimRight () removes the white space on the right

.charat (n) returns the nth character

.concat (value,...) Splicing

.indexOf (substring, start) subsequence position

.substring (from, to) gets the subsequence according to the index

.slice (start, end) slice

.toLowerCase () lowercase

.toUpperCase () uppercase

.split (delimiter, limit) split

(2) characteristics of substirng () and silce ()

String.slice (start, stop) and string.substring (start, stop):

The similarities between the two:

If start equals end, an empty string is returned

If the stop parameter is omitted, the end of the string is taken

If a parameter exceeds the length of string, this parameter is replaced with the length of string

Characteristics of substirng ():

If start > stop, start and stop will be exchanged

If the parameter is negative or not a number, it will be replaced by 0

Characteristics of silce ():

If start > stop does not swap the two

If start is less than 0, the cut begins with the abs (start) character at the end of the string (including the character at that position)

If stop is less than 0, the cut ends at the abs (stop) character (excluding the positional character) from the end of the string to the front.

4. Boolean type

Var a = true;var b = false; "" (empty string), 0, null, undefined, NaN are all false.

5. Array

Similar to the list in Python.

Var a = [123, "ABC"]; console.log (a [1]); / / output "ABC"

(1) Common methods:

The size of the .length array

Append elements to the tail of .push (ele)

.pop () gets the element of the tail

.unshift (ele) header insert element

The .shift () header removes the element

.slice (start, end) slice

.reverse () reversal

.join (seq) concatenates array elements into strings

.concat (val,...) Join array

Sort () sort

(2) sort method

When sorting an array of numeric types, it converts the elements into strings and compares them character by character, so it does not really reflect the size of the element.

Solution: function sortNumber (aformab) {/ / implement a sort function return a-b} stringObj.sort (sortNumber) / / pass the defined sort function into the sort method according to the above rules.

(3) traversing the elements in the array

Var a = [10, 20, 30, 40]; for (var ionome0)

< 5){ console.log("yes");}else { console.log("no");} 2、if-else if-else var a = 10;if (a >

5) {console.log ("a > 5");} else if (a

< 5) { console.log("a < 5");}else { console.log("a = 5");} 3、switch var day = new Date().getDay();switch (day) { case 0: console.log("Sunday"); break; case 1: console.log("Monday"); break; case 2: console.log("Tuesday"); break; case 3: console.log("Wednesday"); break; case 4: console.log("Thursday"); break; case 5: console.log("Friday"); break; case 6: console.log("Saturday"); break;default: console.log("Not is it");} 4、for for (var i=0;i b ? a : b 对应python中的三元运算: a=10b=20n=[x if a>

B else b] print n

VI. Function

1. Function definition

(1) definition of ordinary function

Function F1 () {console.log ("Hello world!");}

(2) functions with parameters

Function f2 (a, b) {console.log (arguments); / / built-in arguments object console.log (arguments.length); console.log (a, b);}

No error will be reported if the passed parameters do not match the number of parameters required:

If the parameters passed are more than needed, only what is needed is retained, and the rest of the parameters are invalid.

If the parameters passed are less than needed, the parameters that are not passed will return undefined.

(3) function with return value

Function sum (a, b) {return a + b;} sum (1,2); / / call the function

(4) Anonymous function mode

Var sum = function (a, b) {return a + b;} sum (1,2)

(5) execute the function immediately

(function (a, b) {return a + b;}) (1,2)

2 、 arguments

Function add (aformab) {console.log (aforb); / / output 3 console.log (arguments.length); / / output 2} add (1Jing 2)

3. Global and local variables of the function.

Local variables:

The variable declared inside the JavaScript function (using var) is a local variable, so it can only be accessed inside the function (the variable's scope is inside the function). As soon as the function finishes running, the local variable is deleted.

Global variables:

The variable declared outside the function is a global variable that can be accessed by all scripts and functions on the web page.

Variable life cycle:

The lifetime of JavaScript variables begins when they are declared. Local variables are deleted after the function runs. Global variables are deleted after the page is closed.

4. Scope

First of all, look for the variable inside the function, and if you can't find it, go to the outer function and find the outermost layer step by step.

(1) example 1 of the scope:

Var city = "BeiJing"; function f () {var city = "ShangHai"; function inner () {var city = "ShenZhen"; console.log (city);} inner ();} f (); / / the output is ShenZhen

The function is divided into definition phase and execution phase.

F ()-> find the defined function execution-> encounter inner ()-> find the defined inner () function execution-> var city = "ShenZhen"-> the result returns ShenZhen

(2) example 2 of the scope:

Var city = "BeiJing"; function Bar () {console.log (city);} function f () {var city = "ShangHai"; return Bar;} var ret = f (); ret (); / / the printed result is BeiJing

Ret ()-> f ()-> execute function f ()-> return Bar---- > execute Bar ()-> Bar () does not declare city---- > find the city---- declared outside the function > the result returns BeiJing

(3) example 3 of the scope of scope:

Var city = "BeiJing"; function f () {var city = "ShangHai"; function inner () {console.log (city);} return inner;} var ret = f (); ret (); / / the output is ShangHai

Ret ()-> f ()-> execute function f ()-> return inner---- > execute inner ()-> inner () there is no declaration in city---- > closure function to find the city---- declared outside the function > the result returns ShangHai

VII. Lexical analysis

An active object, Avtive Object (AO), is formed immediately before the function call, and the following three aspects are analyzed:

1: function parameter, if any, assign this parameter to AO, and the value is undefined. If not, nothing is done.

2: function local variable. If there is a value with the same name on AO, nothing will be done. If not, this variable is assigned to AO with a value of undefined.

3: the function declares that if there is one on AO, the object on AO will be overwritten. If not, nothing is done.

Example 1:

Var age= 18: function foo () {console.log (age); / / AO.age=undefined, the result is undefined var age= 22; console.log (age); / / the result is 22} foo ()

Example 2:

Var age = 18; function foo () {console.log (age); / / the result is function age () {console.log (hehe);} var age = 22; console.log (age) / / the result is 22 function age () {console.log ("hehe");} console.log (age); / / the result is 22} foo (); age () {console.log ("hehe");}

Lexical analysis process:

1. Analyze the parameters. There is one parameter to form an AO.age=undefine.

2. Analyze the variable declaration that there is a var age and find that there is already an AO.age on the AO, so do not do any processing

3. The analysis function declares that if there is a function age () {...} declaration, the original age will be overwritten as AO.age=function () {...}.

Finally, the property on AO has only one age, and the value is declared as a function.

Execution process:

1. When the first console.log (age) is executed, the AO.age is a function, so the first output is a function

2. This var age=22; assigns a value to the attribute of AO.age, so AO.age=22 at this time, so the second output is 2

3. Similarly, the third output is still 22, because there is no statement to change the age value in the middle.

VIII. Built-in objects and methods

Everything in JavaScript is an object: strings, numbers, arrays, dates, and so on. In JavaScript, an object is data that has properties and methods.

We have already taken you through the Number object, String object, Array object and so on in JavaScript when we are learning the basic data types.

Notice the difference between var S1 = "abc" and var S2 = new String ("abc"): typeof S1-- > string and typeof S2-- > Object

1. Custom object

Similar (in some ways) to dictionary data types in Python

Var a = {"name": "Alex", "age": 18}; console.log (a.name); console.log (a ["age"]); content in the traversal object: var a = {"name": "Alex", "age": 18}; for (var i in a) {console.log (I, a [I]);} create object: var person = new Object (); / / create a person object person.name = "Alex" / / name property of person object person.age = 18; / / age property of person object

2. Date object

(1) create a Date object

/ / method 1: do not specify the parameter var D1 = new Date (); console.log (d1.toLocaleString ()); / / 2018-3-18 afternoon 2: console.log 3232 d1.toLocaleString 35pm / method 2: the parameter is the date string var D2 = new Date ("11:12 on 2004-3-20"); console.log (d2.toLocaleString ()); / / the morning of 2004-3-20 11:12:00var D3 = new Date ("04new Date 0320 11:12") Console.log (d3.toLocaleString ()); / 2020-4-3 11 var 12: 00 am / method 3: parameter is millisecond var D3 = new Date (5000); console.log (d3.toLocaleString ()); / / 1970-1-1 morning 8:00:05console.log (d3.toUTCString ()) / / Thu, 01 Jan 1970 00:00:05 GMT// method 4: parameters: year, month, day, hour, minute, millisecond, var d4 = new Date (2004Leijie 20pint 11jade 12j0300); console.log (d4.toLocaleString ()); / / millisecond does not directly show 11:12:00 on 2004-3-20.

(2) the method of Date object:

Var d = new Date ()

GetDate () get date

GetDay () gets the week

GetMonth () get month (0-11)

GetFullYear () gets the full year

GetYear () get year

GetHours () get hours

GetMinutes () get minutes

GetSeconds () get seconds

GetMilliseconds () gets milliseconds

GetTime () returns the cumulative milliseconds (from midnight on 1970-1-1)

3. JSON object (important content)

Var str1 ='{"name": "Alex", "age": 18}'; var obj1 = {"name": "Alex", "age": 18}; var obj = JSON.parse (str1); / / JSON string converted to object var str = JSON.stringify (obj1); / / object converted to JSON string

4. RegExp object (important content)

(1) method 1 for creating regular objects

Parameter 1 regular expression (no spaces)

Parameter 2 matching pattern: commonly used g (global match; find all matches instead of stopping after the first match) and I (ignore case)

The user name can only be English letters, numbers and _, and the first letter must be English letters. The shortest length cannot be less than 6 digits and the longest cannot exceed 12 digits.

Var reg1 = new RegExp ("^ [a-zA-Z] [a-zA-Z0-9] {5dag11} $"); / / create a RegExp object (no spaces after the comma) var S1 = "bc123"; / / the test method of the RegExp object tests whether a string conforms to the corresponding regular rules, and the return value is true or false. Reg1.test (S1); / / true

(2) creation method 2

Var reg2 = / ^ [a-zA-Z] [a-zA-Z0-9 _] {5Jet 11} $/; reg2.test (S1); / / four methods of combining trueString objects with regularities var S2 = "hello world"; s2.match (/ ogamg) / / ["o", "o"] find the regular content in the string s2.search (/ heryg); / / 0 find the content position in the string that conforms to the regular expression s2.split (/ oplag) / / ["hell", "w", "rld"] cuts the string according to the regular expression s2.replace (/ o hells wsrld g, "s"); / / "hells wsrld" replaces the string according to the rule

Note 1:

If the regExpObject has a global flag, the gMagee test () function does not start at the beginning of the string, but at the index specified by the attribute regExpObject.lastIndex.

The value of this property defaults to 0, so the first time you still look from the beginning of the string.

When a match is found, the test () function changes the value of regExpObject.lastIndex to the next index position of the last character of the match in the string.

When the test () function is executed again, the search starts at that index location to find the next match.

Therefore, when we perform a match using the test () function, if we want to re-use the test () function to look from scratch, we need to manually reset the value of regExpObject.lastIndex to 0.

If the test () function can no longer find matching text, the function automatically resets the regExpObject.lastIndex property to 0.

Var reg3 = / foo/g;// at this time regex.lastIndex=0reg3.test ('foo'); / / return true// at this time regex.lastIndex=3reg3.test (' foo'); / / return false// so when we use the test () method to verify whether a string matches exactly, it is not recommended to add the global matching pattern g. Var reg4 = / ^ undefined$/;reg4.test (); / / return truereg4.test (undefined); / / return truereg4.test ("undefined"); / / return true

5. Math object

The absolute value of the number returned by abs (x).

Exp (x) returns the exponent of e.

Floor (x) logarithm is rounded down.

Log (x) returns the natural logarithm of the number (base e).

Max (XBI y) returns the highest values of x and y.

Min (XBI y) returns the lowest of x and y.

Pow (xPowery) returns x to the power of y.

Random () returns a random number between 0 and 1.

Round (x) rounds the number to the nearest integer.

Sin (x) returns the sine of the number.

Sqrt (x) returns the square root of the number.

Tan (x) returns the tangent of the angle.

The above is all the content of the article "what is the use of JavaScript in front of web". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report