current position:Home>Introduction to JavaScript

Introduction to JavaScript

2022-05-15 03:00:09A plant of grass

1、JavaScript Introduction mode

  • One 、 Internal script : take JS The code is defined in HTML On the page .
<script> alert("Hello world"); </script>

stay HTML The document can be anywhere , Place any number of <script>.
Usually put your feet This is placed at the bottom of the element , It can improve the display speed , Because the script execution will slow down the display .

  • Two 、 External script : take JS The code is defined externally JS In file , Then introduce to HTML On the page
    • External file :demo.js

      alert("Hello world");
    • Introduce the outside js file

      <script src="js/demo.js"></script>

      Be careful :

      • External scripts cannot contain <script> label
      • <script> Labels cannot be self closing

2、JavaScript Basic grammar

2.1、 Written grammar

  • Case sensitive .
  • The semicolon at the end of each line is optional
  • notes :
    • Single-line comments :// The comment
    • Multiline comment :/* The comment */
  • Curly braces indicate a block of code .

2.2、 Output statement

  • Use window.alert(“hello JS”) Pop up warning box
  • Use document.write(“hello JS”) write in HTML Output
  • Use console.log(“hello JS”) Write to the console

2.3、 Variable

JavaScript of use var keyword (variable Abbreviation ) To declare variables .

var test=20;
test="hello world";
  • JavaScript It's a weak type language , Variables can hold different types of values .

  • Scope : Global variables .

    	var test;
  • Variables can be defined repeatedly

    var test=10;
    var test=20;
  • ECMAScript6 Added let Keyword to define variables . The usage of definite is similar to var, But the declared variable , Only in let There is an intersection in the code block where the keyword is located , And it is not allowed to repeat the declaration .

  • ECMAScript6 Added const keyword , Used to declare a read-only constant . Once declared , You can't change the value of a constant .

2.4、 data type

  • JavaScript Divided into : Primitive types and reference types
  • 5 Primitive types :
    • number: Numbers ( Integers 、 decimal 、NaN(Not a Number))
    • string: character 、 character string , Single and double citation
    • boolean: Boolean .truefalse
    • null: The object is empty
    • undefined: When the declared variable is uninitialized , The default value for this variable is undefinet.
  • Use typeof Operator can get the data type :alert(typeof age);

2.5、 Operator

JavaScript The following operators are provided . Most and Java Language It's all the same , The difference is JS In relational operators == and ===

  • Unary operator :++,--

  • Arithmetic operator :+,-,*,/,%

  • Assignment operator :=,+=,-=

  • Relational operator :>,<,>=,<=,!=,==,===

  • Logical operators :&&,||,!

  • Ternary operator : Conditional expression ? true_value : false_value

== and === difference

  • ==:

    1. Judge whether the type is the same , If it's not the same , Type conversion

    2. Then compare its value

  • ===:js All in is equal to

    1. Judge whether the type is the same , If it's not the same , Go straight back to false
    2. Then compare its value
var age1 = 20;
var age2 = "20";

alert(age1 == age2);// true
alert(age1 === age2);// false

2.6、 Type conversion

Other types turn to number

  • string Convert to number type : According to the literal value of the string , Turn to numbers . If the face value is not a number , Turn to NaN

  • take string Convert to number There are two ways :

    • Use + Plus operator :
    var str = +"20";
    alert(str + 1) //21
    • Use parseInt() function ( Method ):
    var str = "20";
    alert(parseInt(str) + 1);

    It is recommended to use parseInt() Function transformation .

  • boolean Convert to number type :true To 1,false To 0

    var flag = +false;
    alert(flag); // 0
  • Other types turn to boolean

    • number Type conversion to boolean type :0 and NaN To false, The other figures turn to true
    • string Type conversion to boolean type : Empty string to false, Other strings are converted to true
    • null Type conversion to boolean The type is false
    • undefined Convert to boolean The type is false

2.7、 Flow control statement

JavaScript And Java The same process control statement , as follows

  • if
  • switch
  • for
  • while
  • dowhile

2.8、 function

;JavaScript Function by function Key words to define .
There are two forms of function definition :

  • Mode one :

    function  Function name ( Parameters 1, Parameters 2..){
         Code to execute 
  • Mode two :

    var  Function name  = function ( parameter list ){
         Code to execute 
  • Be careful : Formal parameters do not require type . because JavaScript It's a weakly typed language

    function add(a, b){
        return a + b;

    The parameters of the above function a and b No need to define data types , Because you add... Before each parameter var It doesn't make any sense

  • The return value does not need to define the type , Can be used directly inside the function return Return to

Function call function :

 The name of the function ( List of actual parameters );

Such as

let result = add(10,20);
  • Be careful :JS in , Function calls can pass any number of parameters
    for example let result = add(1,2,3);
    It is to put data 1 Passed to variable a, Put the data 2 Passed to variable b, And data 3 No variables are received .

3、JavaScript Common objects


3.1.1、 Define format

There are two formats for defining arrays :

  • The way 1

    var  Variable name  = new Array( List of elements ); 

    for example :

    var arr = new Array(1,2,3); //1,2,3  Is the data stored in the array ( Elements )
  • The way 2

    var  Variable name  = [ List of elements ];

    for example :

    var arr = [1,2,3]; //1,2,3  Is the data stored in the array ( Elements )

    Be careful :Java The static initialization of the array in uses {} Definition , and JavaScript Is used in [] Definition

3.1.2、 Element access

Access the elements and... In the array Java The language is the same , The format is as follows :

arr[ Indexes ] =  value ;

Code demonstration :

 //  Mode one 
var arr = new Array(1,2,3);
// alert(arr);

//  Mode two 
var arr2 = [1,2,3];

//  visit 
arr2[0] = 10;

3.1.3、 characteristic

JavaScript The array in is equivalent to Java Middle set . The length of an array can vary , and JavaScript Weak type , So you can store any type of data .

For example, the following code :

//  Lengthening 
var arr3 = [1,2,3];
arr3[10] = 10;
alert(arr3[10]); // 10
alert(arr3[9]);  //undefined

The above code gives three elements in the definition array , Another index is 10 Added data to the location of 10, that Indexes 3 To Indexes 9 What is the element of position ? We introduced before , stay JavaScript If there is no assignment in , The default is undefined.

If arr3 Add string data to the array , It can also be added successfully

arr3[5] = "hello";
alert(arr3[5]); // hello

3.1.4、 Properties and methods

 Insert picture description here

push function : Add elements to the array , That is, adding elements to the end of the array

The parameter represents the element to be added .

// push: Add method 
var arr5 = [1,2,3];
alert(arr5);  // The elements of an array are  {1,2,3,10}

splice function : Remove elements
Parameters 1: Indexes . Indicates the index location from which to delete
Parameters 2: Number . Means to delete several elements

// splice: Remove elements 
var arr5 = [1,2,3];
arr5.splice(0,1); // from  0  The index position starts to be deleted , Delete an element  
alert(arr5); // {2,3}


String There are two ways to create objects :

  • Mode one :
    var  Variable name  = new String(s); 
  • Mode two :
    var  Variable name  = " Array "; 

attribute :length Length of string
Method :
charAt() Return fee Positional characters .
IndexOf() Retrieve string .

  • String Object also has a function trim() , This method is not reflected in the document , But all browsers support ; It is used to remove spaces at both ends of a string .

3.3、 Custom object

Custom object format :

var  Object name  = {
     The attribute name 1: Property value 1,
     The attribute name 2: Property value 2,
     The name of the function :function ( Parameter list ){

The format of the calling property :

 Object name . Property name 

The format of the calling function :

 Object name . Function name ()

JavaScript Examples of custom objects in :

var person = {
        name : "zhangsan",
        age : 23,
        eat: function (){
            alert(" Dry rice ~");

alert(;  //zhangsan
alert(person.age); //23;  // Dry rice ~


  • BOM:Browser Object Model Browser object model . That is to say JavaScript Encapsulate the components of the browser as objects .
  • If we want to operate the various components of the browser, we can operate BOM To implement .
  • such as : Now I want to change the address in the browser address bar to You can use BOM As defined in Location Object's href attribute , Code : location.href = "";

BOM Contains the following objects :

  • Window: Browser window objects
  • Navigator: Browser object
  • Screen: Screen objects
  • History: The object of history
  • Location: Address bar object
    The picture below is BOM The corresponding relationship between each object in the browser and each component of the browser
     Insert picture description here
    BOM Medium Navigator Objects and Screen Objects basically don't use

4.1、 Window object

window The object is JavaScript An object that encapsulates the browser's window .

4.1.1、 obtain window object

This object does not need to be created to be used directly window, among window. It can be omitted . For example, we used alert() function , In fact, that is window Object function , The call can be written in the following two ways .

  • Use... Explicitly window Object call
  • Implicit call

4.1.2、 window Object properties

window Object provides a way to get other BOM The properties that make up the object .

  • history
  • Location
  • Navigator
  • Screen

in other words , We want to use Location Object words , You can use window Object acquisition ; It's written in window.location, and window. It can be omitted , Simplified writing location To get Location object .

4.1.3、window Object functions

window Object common functions :

setTimeout(function, Millisecond value ) : After a certain time interval, execute a function, Only once
setInterval(function, Millisecond value ) : After a certain time interval, execute a function, Loop execution

Timer code demonstration :

// Call it once 
setTimeout(function (){
// Cycle call 
setInterval(function (){

4.2、History object


History The object is JavaScript An object that encapsulates history .

  • History Object acquisition
    Use window.history obtain , among window. It can be omitted
  • History Object function
     Insert picture description here

4.3、Location object

Location The object is JavaScript The object encapsulated in the address bar . You can manipulate the object , Jump to any page .

4.3.1、 obtain Location object

Use window.location obtain , among window. It can be omitted

window.location. Method ();
location. Method ();

4.3.2、Location Object properties

Location Object provides a pair of properties . There is only one attribute commonly used in the future href
 Insert picture description here

alert(" It's time to jump ");
location.href = "";

3 Jump to Baidu in seconds

    document.write("3 Jump to the home page in seconds ...")


5.1 、 summary

DOM:Document Object Model Document object model . That is to say JavaScript take HTML The various components of the document are encapsulated as objects .

DOM In fact, we are not new , Before learning XML I've been in contact with , It's just XML The tags in the document need us to write code to parse , and HTML The document is parsed by the browser . The encapsulated objects are divided into

  • Document: The entire document object
  • Element: Element object
  • Attribute: Property object
  • Text: Text object
  • Comment: annotation objects

effect :

JavaScript adopt DOM, You can be right HTML It's working

  • change HTML Content of element
  • change HTML Style of element (CSS)
  • Yes HTML DOM Respond to events
  • Add and remove HTML Elements

DOM Relevant concepts :

DOM yes W3C( World wide web consortium ) Access defined HTML and XML Standards of documents . The standard is divided into 3 Different parts :

  1. The core DOM: A standard model for any structured document . XML and HTML Common standards

    • Document: The entire document object

    • Element: Element object

    • Attribute: Property object

    • Text: Text object

    • Comment: annotation objects

  2. XML DOM: in the light of XML Standard model for documentation

  3. HTML DOM: in the light of HTML Standard model for documentation

    The standard is at the core DOM On the basis of , Yes HTML Each tag in is encapsulated into a different object

    • for example :<img> The tag is encapsulated into... When the browser is loaded into memory Image object , At the same time, the object is also Element object .
    • for example :<input type='button'> The tag is encapsulated into... When the browser is loaded into memory Button object , At the same time, the object is also Element object .

5.2、 obtain Element object

HTML Medium Element Objects can pass through Document Object acquisition , and Document The object is through window Object acquisition .

Document Object provides the following access Element Function of element object

  • getElementById(): according to id Property value get , Returns a single Element object
  • getElementsByTagName(): Get... According to the tag name , return Element An array of objects
  • getElementsByName(): according to name Property value get , return Element An array of objects
  • getElementsByClassName(): according to class Property value get , return Element An array of objects

6、 Event monitoring

6.1 Event binding

JavaScript Two event binding methods are provided :

  • Mode one : adopt HTML The event attribute in the tag is bound

    Like the following code , There is a button element , We define on this label Event properties , Bind the function in the event attribute .onclick Namely Click events The event properties of .onclick='on()' It indicates that the click event is bound with a file named on() Function of

    <input type="button" onclick='on()>

    The following is the binding of click events on() function

    function on(){
    	alert(" I was ordered ");
  • Mode two : adopt DOM Element attribute binding
    For example, the following code is the button label , We don't use... On this label Event properties , The operation of binding events needs to be performed in js In the code

    <input type="button" id="btn">

    below js The code is to get id='btn' The element object of , And then onclick As an attribute of the object , And bind anonymous functions . This function is automatically executed after the event is triggered

    document.getElementById("btn").onclick = function (){
        alert(" I was ordered ");

6.2、 Common events

Event property name explain
onclick Mouse click event
onblur Element losing focus
onfocus Element gets focus
onload A page or image is finished loading
onsubmit This event is triggered when the form is submitted
onmouseover The mouse is moved over an element
onmouseout Move the mouse away from an element

7、 Regular expressions

Concept :

  • Regular expressions define the rules of character composition .

Definition :

  • Direct measurement : Be careful not to use quotation marks

    var reg=/^\w{6,12}$/;
  • establish RegExp object

    var reg=new RegExp("^\\w{6,12}$");

Method :

  • test(str) : Judge whether the specified string conforms to the rules , return true or false

The common rules for regular expressions are as follows :

  • ^: To begin

  • $: End of the said

  • [ ]: Represents a single character in a range , such as : [0-9] Single digit characters

  • .: Represents any single character , Except for line breaks and line terminators

  • \w: Characters representing words : Letter 、 Numbers 、 Underline (), amount to [A-Za-z0-9]

  • \d: Represents a numeric character : amount to [0-9]

quantifiers :

  • +: At least one

  • *: Zero or more

  • ?: Zero or one

  • {x}:x individual

  • {m,}: At least m individual

  • {m,n}: At least m individual , most n individual

    var reg=/^\w{6,12}$/;
    var str="123abc";
    var flag=reg.test(str);

copyright notice
author[A plant of grass],Please bring the original link to reprint, thank you.

Random recommended