JavaScript
1. What is JavaScript
It is used for simple logic of front-end pages and interaction with back-end pages
- JavaScript (JS for short) is a lightweight, interpretive or just in time compiler with function priority programing language . Although it is developed as Web Page scripting language It is famous, but it has also been used by many non-governmental organizations browser In the environment, JavaScript is based on prototype programming, multi paradigm dynamic scripting language, and supports object-oriented , imperative, declarative function Open programming paradigm.
- JavaScript was created in 1995 by Netscape Brendan Eich of the company was designed and implemented on Netscape Navigator browser for the first time. Because Netscape and Sun In cooperation, Netscape management wanted it to look like Java, so it was named JavaScript. But in fact, its grammatical style is different from Self and Scheme Closer.
- The standard for JavaScript is [ECMAScript]( https://baike.baidu.com/item/ECMAScript /1889420). As of 2012, all browsers fully support ECMAScript 5.1, and older browsers support at least ECMAScript 3 standard. On June 17, 2015, ECMA International released the sixth edition of ECMAScript. The official name of this edition is ECMAScript 2015, but it is usually called ECMAScript 6 or ES2015.
2. Introduction
JS code is usually placed in the html file < head > or at the bottom of < body >
JS code needs to be placed in the < script > tag
1. JS code usage
Internal use:
<script> alert('hello,word');//Popup </script>
References:
<script src="js/01-alert.js"></script>
2. Debugging method
<script> let i = 1;//Define a local variable alert(i);//Output through web pop-up window console.log(i);//Output via web console </script>
The web console uses js code
3. Data type
(1). Definition of variables
<script> 'use strict';//Use strict check mode let i = 1;//local variable var j = 1;//global variable /* * var All data types can be defined * number(Integer, float, negative) * String ('string ','string') * Boolean(true,false) * Logical operator * * Comparison operator * ==(Only need type equal to) * ===(Type and value are equal to) * =(Equal to) * */ </script>
(2). character string
(3). array
Array elements can contain any data type
<script> 'use strict'; let arr = [1,2,"123",1.0]; console.log(arr); </script>
common method
. lenght returns the length of the array
. pop() pops the last element of the array
. push() pushes in elements at the end of the array
. slice() intercepts elements from the start bit to the end bit
. indexOf() gets the subscript of the specified element
. unshift() array header push in element
. shift() pops up the array header element
. sort() sorts the array elements
. reverse() inverts the array elements
. concat() concatenates an array with an array
. join() uses the symbol in parentheses to connect array elements when printing
(4). object
Object definition
Assignment of object properties
Value of object attribute
JS object can realize dynamic element addition and deletion
Common methods:
Judge whether a property exists in the object (the property inherited from the parent class will also return true)
Determine whether an attribute is an object's own attribute
Object definition
<script> 'use strict' var person = { name: "xiaozhang", age: 21, school: "xxx university" } </script>
Object value and assignment
person.name 'xiaozhang' person.name = "Xiao Zhang" 'Xiao Zhang'
Dynamic addition and deletion properties of object
person.sex = "male"//Add attribute 'male' person {name: 'Xiao Zhang', age: 21, school: 'xxx university', sex: 'male'} delete person.sex//Delete attribute true person {name: 'Xiao Zhang', age: 21, school: 'xxx university'}
Common judgment
person {name: 'Xiao Zhang', age: 21, school: 'xxx university'} 'toString' in person true person.hasOwnProperty('toString') false person.hasOwnProperty('name') true
(5). Process control
if()
while()
do{} while()
for loop
Traversing array elements forEach, for of
Traversal array subscript for in
var arr = [11,2,123,3,12,3,123,12,3,1,23]; arr.forEach(function (value) { console.log(value); })var arr = [1,2,3,4,5]; //forEach traverses array elements arr.forEach(function (value) { console.log(value); }) //for of traversal array elements for (let number of arr) { console.log(number) } //for in traversal array subscript for (let number in arr) { console.log(number) }
(6).Map and Set
definition
Value assignment
map.set('kye',value)
map.get('key')
set.add()
delete
map.delete('kye')
set.delete()
Whether to save an element in set
set.has()
for of is required to traverse Map and Set
var map = new Map([['Xiao Zhang',100],['Xiao Wang',80]]); var set = new Set([1,1,1,22,22,3,3]); //Traverse map and set for (let x of map) { console.log(x); } console.log("===============") for (let x of set) { console.log(x); }
4. Functions
(1). Define function
Two methods of defining functions
Function call
How to throw an exception manually
Acquisition and processing of multiple input parameters
Two ways to define parameters
<script> function ab(x) { console.log(x); } let abc = function(x){ console.log(x); } </script>
Throw exception manually
//Judge whether the input parameter is a number, otherwise an exception will be thrown function a1(x){ if(typeof x !== 'number'){ throw 'Not a Number!' }else{ return x; } }
Processing of multiple input parameters
'use strict' function a1(x){ console.log(x); if (arguments.length > 1){//arguments can get all the input parameters as an array for (let i = 0; i< arguments.length ; i++) { console.log(arguments[i]); } } } function a2(x,...rest) {//The extra participants are stored in rest as an array console.log(x); console.log(rest); }
(2). Scope of variable
javascript will automatically promote the definition of all variables to the front
When writing javascript, pay attention to putting all variable definitions first
global variable
Can be used in all functions
Global object window
<script> 'use strict'; var x = 23;//This is a global variable console.log(x); console.log(window.x);//window represents the global object and can obtain all global variables and functions </script>
All self-defined methods and functions are stored in their own defined global objects
<script> var MyAppObject = {};//Define unique global variables MyAppObject.name = 'Xiao Zhang';//Add attributes to your global variables MyAppObject.add = function (newName) {//Add functions to your global variables MyAppObject.name = newName; return newName; } </script>
Local scope let, constant const (read-only variable)
(3). method
It is understood that the function defined in the object is the method
<script> 'use strict'; var person = { name:'Xiao Zhang', birth:2020, age: function () { let now = new Date().getFullYear(); return now-this.birth; } } </script>
this keyword points to the object that calls the current function
You can use the Apply method to specify the object pointed to by this of a method
<script> 'use strict'; function getAge() { let now = new Date().getFullYear(); return now-this.birth; }; var person = { name:'Xiao Zhang', birth:2020, age: getAge() } getAge();//Because the object calling this function becomes window, the birth attribute under this keyword cannot be found getAge().apply(person,[]);//Use apply to specify an object to use the this keyword </script>
5. Internal object
Standard object
typeof is used to judge the data type - basic data type:
number,String,boolean,object,function,undfined
(1).Date
<script> 'use strict'; var date = new Date();//date represents the current time date.getFullYear();//particular year date.getMonth();//Month 0 ~ 11 date.getDate();//What number date.getDay();//Number of weeks date.getHours();//hour date.getMinutes();//minute date.getMilliseconds()//second date.getTime();//time stamp date.toLocaleDateString();//Get the current time var newDate = new Date(1641034918057);//Read time by timestamp </script>
(2).JSON
definition
- JSON(JavaScript Object notation (JS object notation) is a lightweight data exchange format.
- It is based on ECMAScript (js specification developed by the European Computer Association) uses a text format completely independent of the programming language to store and represent data.
- The concise and clear hierarchy makes JSON an ideal data exchange language. It is easy for people to read and write, but also easy for machine analysis and generation, and effectively improves the network transmission efficiency.
effect
'use strict'; var obj = { name:"Xiao Zhang", age: 20, sex:"male" } var newObj = JSON.stringify(obj);//Convert object to string var oldObj = JSON.parse('{"name":"Xiao Zhang","age":20,"sex":"male"}');//Convert string to object
6. Object oriented programming
ES6 was introduced
The idea of using classes before ES6 requires the use of prototypes. The syntax is not very convenient, and it is not hi and friendly to the back end
Therefore, the writing method of Java classes is introduced in ES6, which is essentially the use of prototype objects, but the writing method is basically the same as that of Java
Object oriented thought
- Everything is object
- Class is the abstraction of object and the idea of prototype object in template JS
- An object is a concrete instance of a class and has its own characteristics
(1). Define class
<script> //Define a student class class Student { constructor(name) { this.name=name; } hello(){ alert('hello'+' '+this.name); } } //Two objects var xiaoming = new Student("xiaoming"); var xiaowang = new Student("xiaowang"); </script>
(2). Inheritance class
//Inherit Student class class Pupil extends Student{ constructor(name,school) { super(name); this.school = school; } mySchool(){ alert(this.name+'='+this.school); } } //An object var pupil1 = new Pupil('Xiaohe','Sunshine primary school');
(3). Prototype chain
- In JavaScript, everything is an object, and there is a relationship between objects, which does not exist in isolation.
- In JavaScript, the inheritance relationship between objects points to the parent Object through the prototype Object until it points to the Object object, which forms a prototype pointing chain, which is called the prototype chain in professional terms.
- person → Person → Object