current position:Home>Introduction to JavaScript
Introduction to JavaScript
2022-05-15 03:00:09【A plant of grass】
List of articles
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
- External scripts cannot contain
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 */
- Single-line comments :
- 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; } alert(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 tovar
, 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 citationboolean
: Boolean .true
、false
null
: The object is emptyundefined
: When the declared variable is uninitialized , The default value for this variable isundefinet
.
- 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
==:
Judge whether the type is the same , If it's not the same , Type conversion
Then compare its value
===:js All in is equal to
- Judge whether the type is the same , If it's not the same , Go straight back to false
- 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 .- Use
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 examplelet 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、Array
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];
//alert(arr2);
// visit
arr2[0] = 10;
alert(arr2)
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
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];
arr5.push(10);
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}
3.2、String
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(person.name); //zhangsan
alert(person.age); //23
person.eat(); // Dry rice ~
4、BOM
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
https://www.itheima.com
You can use BOM As defined inLocation
Object'shref
attribute , Code :location.href = "https://itheima.com";
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
BOM MediumNavigator
Objects andScreen
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
window.alert("abc");
- Implicit call
alert("abc")
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 oncesetInterval(function, Millisecond value )
: After a certain time interval, execute a function, Loop execution
Timer code demonstration :
// Call it once
setTimeout(function (){
alert("hehe");
},3000);
// Cycle call
setInterval(function (){
alert("hehe");
},2000);
4.2、History object
4.2.1、
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
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
alert(" It's time to jump ");
location.href = "https://www.baidu.com";
3 Jump to Baidu in seconds
<script>
document.write("3 Jump to the home page in seconds ...")
setTimeout(function(){
location.href="https://www.baidu.com"
},3000);
</script>
5、DOM
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 objectElement
: Element objectAttribute
: Property objectText
: Text objectComment
: 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 :
The core DOM: A standard model for any structured document . XML and HTML Common standards
Document
: The entire document objectElement
: Element objectAttribute
: Property objectText
: Text objectComment
: annotation objects
XML DOM: in the light of XML Standard model for documentation
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 memoryImage
object , At the same time, the object is alsoElement
object . - for example :
<input type='button'>
The tag is encapsulated into... When the browser is loaded into memoryButton
object , At the same time, the object is alsoElement
object .
- for example :
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 objectgetElementsByTagName()
: Get... According to the tag name , return Element An array of objectsgetElementsByName()
: according to name Property value get , return Element An array of objectsgetElementsByClassName()
: 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
NamelyClick events
The event properties of .onclick='on()'
It indicates that the click event is bound with a file namedon()
Function of<input type="button" onclick='on()’>
The following is the binding of click events
on()
functionfunction 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 labelEvent 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 thenonclick
As an attribute of the object , And bind anonymous functions . This function is automatically executed after the event is triggereddocument.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);
alert(flag);
copyright notice
author[A plant of grass],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/132/202205120011381824.html
The sidebar is recommended
- React error report record
- Analysis of react life cycle function
- react demo1 TodoList
- Summary of the differences between state and props in react
- Difference between controlled components and uncontrolled components in react
- Node. JS use get Stream download file
- How does JavaScript copy arrays instead of references
- JavaScript calculates the number of days, hours, minutes and seconds between days
- JQuery get page address parameters
- JavaScript create Download
guess what you like
node. JS traversal directory
Tips for using JavaScript string split (how to keep the delimiter)
Common CSS notes
JavaScript usage Get the address of the regular function
New generation node JS web development framework koa zero foundation entry learning notes
JavaScript notes
asp. Net core method for modifying HTML without rerun
Summary of compatibility processing of H5 + Vue cli project in Safari browser
Summary of amap scheme of Gaode map used in vue3 + TS project
Summary of filter scheme used in JS code in Vue
Random recommended
- Build an electron project based on Vue from scratch
- In Vue project, solve the problem of verification conflict when eslint and prettier are used at the same time
- Vue3 + vuecli4 solve chunk vendors JS file is too large. Scheme summary
- Scheme summary of eslint check before vue3 + vite configuration project operation and eslint check before git submission
- Fatal authentication failed for 'httpxxxx Git 'solution
- Vue's solution to the compatibility of hevc encoded video in each end browser
- Record the solution to the error in obtaining the picture in springboot in Vue
- [Vue] detailed analysis of the life cycle function of Vue components
- [Vue] deeper understanding of user-defined attribute props
- [Vue] front end error: cannot read properties of undefined (reading 'split')
- [Vue] asynchronous problem of component value transfer -- the sub component gets the data slowly
- [Vue] Vue data changes, but the page is not updated in real time
- [element UI] use of form verification -- detailed explanation
- [Vue] use of slots - Review
- The influence on the fixed positioning element of the inner layer when the outer element has a fixed height and overflows and rolls
- Precautions
- Change detection strategy of angular component
- Angular service and @ injectable
- JS, HTML and CSS are not compatible and do not use common knowledge
- Properties to be known in angular @ component
- Angular acquisition and operation DOM
- Html2canvas problem
- Use day in Vue JS (time and date processing library)
- Vue cli configuring preprocessor global variables (take less as an example)
- How to use H5 custom tags in Vue?
- Come on, vue2 customize global loading
- Come on, Vue move the end suspension ball assembly
- React routing foundation and transmission parameters
- Come on, Vue graphic verification code component
- JavaScript judges browser types and kernels at home and abroad (including 360, QQ, Sogou, etc.)
- ArcGIS JavaScript 4. Generates a rectangular buffer at the point of X
- Node under window JS installation, environment configuration, setting Taobao image
- Understanding of prototype and prototype object of JavaScript
- How to customize the startup port of react project!
- Why vue3 0 using proxy to realize data listening 2021-06-21
- Front end artifact - download, configuration and use process of Charles (vase) [Mac version]
- React next configures SVG loader and supports SVG configurability
- React native Android phone cannot be opened after installation. Flash back!
- Fetch and Axios failed to request on Android, with error messages: network request failed and network error
- How to upgrade react Babel 7.1.0