js introduction
JavaScript is one of the three languages that web developers must learn. It is an object-oriented and event driven web scripting language based on client browser developed by Wangjing company (Script means Script)
Scripting language: no compilation is required. The js interpreter (js engine) interprets and executes it line by line during operation
js type
Simple / basic / raw data type
number (numeric), string (string), boolean (boolean), undefined (undefined), null (empty)
Complex data type
object, RegExp, function, Array, Date, constructor
Difference: storage location in memory
-
Access to basic data types occurs in stack memory
-
The reference type saves the data in the heap and the address (Reference) of the data in the heap in the stack
Dataset type conversion
-
Implicit type conversion
-
Operation process (e.g - / *)
-
-
Cast type
-
Number() (converted to numeric)
-
String() (convert to string)
-
parseInt() rounding Cast to number. If the first number is not a number, NaN is returned. There can be spaces at the beginning and end
-
parseFloat() Returns a floating point number And cast to number There can be spaces at the beginning and end NaN if the first number is not a number
-
toString() Cast to string
-
operator
-
Arithmetic operator
+ - * / %
++ --
be careful:
1. The self increasing and self decreasing operators are pre and post, which has no effect on the variable itself
2. During assignment:
(1) Operator, first operation, then assignment
(2) Operator, assignment before operation
-
Logical operator
&&
||
!
Extension:
False: false, 0, null, undefined, ''
True: other
Logical operator extension: if non Boolean types appear on both sides of the logical operator, the result is not necessarily Boolean
||:
If the first is false, the result is the second
The first is true and the result is the first (short circuit)
&&:
If the first is false, the result is the first
If the first is true, the result is the second
-
Comparison operator
> < == ===
greater than less than be equal to All equal
<= >= != !==
Less than or equal to Greater than or equal to Not equal to Not all equal to
-
Assignment Operators
= += -= /= *= %=
1.a=2;
2.a=a+1; // a +=1;
3.a=a-1; // a -=1;
4.a=a/1; // a /=1;
5.a=a*1; // a *=1;
6.a=a%1; //a %=1;
-
Ternary operator
Condition code 1: Code 2
Synchronous and asynchronous
Synchronization: executed in sequence, blocking
Asynchronous: not necessarily in order, not blocking
Note: synchronization and asynchrony occur at the same time. Execute synchronization first
//asynchronous // setTimeout(function () { // console.log(1); // }, 100) // setTimeout(function () { // console.log(2); // }, 50) // setTimeout(function () { // console.log('2'); function getData(fn) { let a; setTimeout(function () { a = 10 //A copy of data given by the server 10 fn(a) },1000) // return a; } // var num = getData() // console.log(num);//?? undefined //10??? getData(function(num){ //Callback function console.log(num); }) //Solve the problem of asynchronous parameter transfer: callback function
array
Array is an object type
General method of array
//1.concat Merge array
// var arrx=arr.concat(arr1,arr1,arr1)
var arrx=arr.concat() // copy
console.log(arrx);
//2.push Add element at the end of array
//3.splice Delete, add, replace
// arr.splice(1,1) // delete
// arr.splice(1,3)
// arr.splice(1,0,'hello',"word") // add to
arr.splice(1,1,'hello') // replace
//4.slice Intercept array
var arrx=arr.slice(1,2) // [start,end) Cannot get end
//5.pop Delete the element at the end of the array
//6.shift Delete array header element
//7.unshift Add element to header
//8.indexOf Gets the index of the element in the array
//9.lastIndexOf Gets the index of the element in the array, starting at the end
//10.sort sort Sort by ASCII by default
//11.reverse
//12.join
//...
extend
//Chinese character sorting arr.sort (function(a,b){ return a.name.localeCompare(b.name) }) console.log(arr);
Iterative method of array
-
The return value of some is Boolean
-
The return value of every is Boolean
//some every
// some returns true if one of the elements in the array meets the conditions, and false if none of them meet the conditions
// Every returns true if every element in the array meets the conditions, and false if one element does not meet the conditions
var scores = [80, 100, 90, 77]
// Q: have you passed?
// var count=0
// for(var i=0;i<scores.length;i++){
// if(scores[i]>=60){
// count++
// }
// }
// var rst=scores.every(function(item){
// return item>=60 // Really
// })
var rst = scores.every(item => item >= 60) //???
console.log(rst);
// [true, true, true, false, true,,]
// Q: are there any students who fail?
// var rst=scores.some(function (value, index) {
// // console.log(value, index);
// return value < 60
// })
// console.log(rst);
- ilter filters the data that meets the conditions, forms a new array, and returns a new array
// var arr = [10, 20, 100, 99, 88, 55, 40, 30]
// // Filter out data greater than 60
// var arr0=arr.filter(function (item, index) {
// // console.log(item,index);
// return item >= 60
// })
// console.log(arr0);
var datas = [
{no: 1001, name: "dog egg", age: 20},
{no: 1002, name: "Lv Bu", age: 33},
{no: 1003, name: "Cai Wenji", age: 18},
{no: 1004, name: "steel gun", age: 50}
]
var ps=datas.filter(function (item) {
return item.age > 30
})
-
map returns a new array after processing the original array data
// var arr = [10, 20, 100, 99, 88, 55, 40, 30]
// var newArr=arr.map(function (item) {
// // return item + 5
// if(item<60){
// return item+5
// }
// return item
// })
// console.log(newArr);
var datas = [
{no: 1001, name: "dog egg", age: 20},
{no: 1002, name: "Lv Bu", age: 33},
{no: 1003, name: "Cai Wenji", age: 18},
{no: 1004, name: "steel gun", age: 50}
]
// var data=datas.map(function(item){
// item.age=item.age-2
// return item
// })
var data = datas.map(function (item) {
item.sex = 0 // New attribute
return item
})
console.log(data);
-
reduce receives a function as an accumulator. Each value in the array (from left to right) is reduced and finally calculated as a value
// var arr = [10, 20, 20, 30, 10, 100]
// // var sum = arr.reduce(function (a, b) { // A is the first array in the array, and B is the second data
// // console.log(a, b); // After the second time, the value of a is the sum of the previous data
// // return a + b
// // })
// var sum = arr.reduce(function (a, b) { // A is the first array in the array, and B is the second data
// console.log(a, b); // After the second time, the value of a is the sum of the previous data
// return a * b
// })
// console.log(sum);
// for (var i = 0; i < arr.length; i++) {
// sum += arr[i]
// }
var arr = [[10, 20, 30], ['hello'], [50, 100], [40], [70, 11, 22]]
// Transform an array into a one-dimensional array
var arrx = arr.reduce(function (a, b) {
return a.concat(b)
})
function
Callback function
Ordinary function
Higher order function: a function that can receive a function as a parameter
function show(fn) { //fn callback function show: higher order function console.log(fn); } show(function(){ console.log('hello world'); })
Self executing function
Anonymous function
Function without name
Anonymous functions cannot be used directly
//Application scenarios of anonymous functions: methods of event functions, callback functions and objects var obj = { name: "tearful", say: function () { console.log('Ha ha ha'); } }
Anonymous function self execution
(function() { console.log('Ha ha ha'); })();
Suggestion: add a semicolon before anonymous function self execution;
1.3 closure
Closure: access to variables in the scope of another function within one function (return the function)
Closure is a bridge between the inside and outside of the connected function, which can realize the resident memory of local variables.
Closure common interview questions:
var arr = []; for (var i = 0; i < 3; i++) { (function (i) { arr.push(function () { console.log(i); }) })(i) } // console.log(arr); arr[0]() arr[1]() arr[2]()
Example:
var lis = document.querySelectorAll("ul li") // for(var i=0;i<lis.length;i++){ // // lis[i].index=i; // lis[i].onclick=function(){ // console.log(this.index); // } // } for (var i = 0; i < lis.length; i++) { (function (a) { lis[a].onclick = function () { console.log(a); } })(i); // (function (i) {//0 // lis[i].onclick = function () { // console.log(i); // } // })(0); // (function (i) {//1 // lis[i].onclick = function () { // console.log(i); // } // })(1); // (function (i) {//2 // lis[i].onclick = function () { // console.log(i); // } // })(2); // (function (i) { // lis[i].onclick = function () { // console.log(i); // } // })(3); }
recursion
A common algorithm idea:
Factorization:
//recursion //Factoring function fn(n){ if(n==1){ return 1; } return n*fn(n-1); } console.log(fn(10)); 10*fn(9)
Example: Print Yang Hui triangle:
for (var i = 1; i < 9; i++) { //that 's ok for (var j = 1; j <= i; j++) {//column document.write(cal(i, j) + " ") } document.write("<br>") } //Calculation of numbers function cal(m, n) { //First row, first column, last column if (m == 1 || n == 1 || m == n) { return 1; } return cal(m - 1, n) + cal(m - 1, n - 1) }
1.5 call and apply
this points to different places.
In the global, this points to window
Point to the event caller in the event function
In the method of the object, this points to the object (this points to the caller, who calls, and who this points to)
Both call and apply can modify the problem of this pointing in the function (the functions are consistent, but the usage is inconsistent)
-
call(obj, parameter 1, parameter 2, parameter 2)
-
apply()
// function show(){ // console.log(this); // } function show(a,b){ console.log(this,a,b); } // show(); // show.call({}) ;// No parameter show.call({},10,20) show.apply({}, [10, 20])
object-oriented
Object: everything is an object, the abstraction of things
Instances: instantiation of objects
create object
-
Custom object (new object)
-
Literal / json var obj = {}
-
Factory function
-
Constructor
//Constructor function Person(name, age, addr) { this.name = name; this.age = age; this.addr = addr; this.say = function () { console.log(this.name + "Hello"); } } //New function? Create object Assign the scope of the constructor to the new object Add properties and methods for the new object and return the new object // var p1=new Person('tianqi ', 20); // console.log(p1); // console.log(p1 instanceof Person);
-
Prototype mode
-
Prototype prototype all objects contain a prototype property, which is used to save the public properties and methods of the object
-
Object.ptotype
-
Object instance__ proto__
-
-
The properties of the constructor prototype object point to the constructor
Features: attributes are placed in the prototype and become public attributes
-
-
Mixed mode
Constructor + prototype
function Person(name,age,no){ this.no=no; this.name=name this.age=age; } Person.prototype.say=function(){ console.log(this.name+" Ha ha ha"); } Person.prototype.walk=function(){ console.log(this.name+" Run and fly......"); } var p1=new Person("First Emperor of Qin",55,'001') var p2=new Person("eunuch who conspired with Li Si to influence the succession to the First Emperor",56,'002')
-
Dynamic mixing
-
//Dynamic mixing function Person(name, age, no) { this.no = no; this.name = name this.age = age; console.log(typeof this.say); //method if (typeof this.say != 'function') { Person.prototype.say = function () { console.log(this.name + " Ha ha ha"); } } // Person.prototype.walk = function () { // console.log(this.name + "flying..."; // } }