JavaScript self study notes of must see articles

  • 2021-07-01 06:05:19
  • OfStack

0-Determine whether variables and parameters are initialized


if(x){} // The variable is initialized or the variable is not empty or the variable is not zero 

1-Declare functions that do not need to declare return values, parameter types, or even'end of sentences'; '


function sum(i1,i2){return i1+i2}

2-Declare anonymous functions directly and use them immediately


var f=function(i1,i2){return i1+i2;}; alert(f(1,2));// Ordinary anonymous function 

alert(function(i1,i2){return i1+i2;}(3,4));// Direct declaration , Use immediately 

There is no class concept in 3-js, so some methods look like classes


function Person(name,age){

this.Name=name;// Dynamically add attributes, similar to C# In dynamic A = new ExpendoObject();

this.Age=age;

this.SayHello=function(){alert('Hello,My name is '+name+' I am '+age+' years old.')};

}

var p1=new Person('lorry',21);

p1.SayHello(); // Image class 1 Sample call 

p1.Gender=' Male ';    // Dynamic increase of'gender ' ' Attribute 

alert(p1.Gender);

4-Array objects are arrays, and you don't have to define arrays in advance


var arr=new Array();

arr[0]=0;

arr[1]=1;

arr[2]=2;

for(var i=0;i<=arr.length-1;i++){

alert(arr[i]);

}

5-Array is an array, also Dictionary, also Stack


var dict=new Array();// As Dictionary Use 

dict[' I ']='wo';

dict[' Love ']='ai';

dict[' You ']='ni';

alert(dict[' I ']); // Called by key value 

alert(dict. Love ); // Like calling properties 1 Sample call (feature of dynamic language) 

 

for(var k in dict){ //js Traversal in 

 alert(k);  //' I ' , ' Love ' , ' You '--> What is printed out is key

}

for(var k of dict){ //js Traversal in 

 alert(k);  //'wo' , 'ai' , 'ni'--> What is printed out is value

}

var arr = [1,2,3,4,5];//Array Simplified creation method of 

var arr = {"lorry":21,"cloud":20};// How to create dictionary style 

6-Traverse through all elements that the current page can call


var s=null;

for(var k in document){// The properties of the object are all set in the key Appearing in the form of 

 s+=k+" ;";

}

alert(s);

7-Use an Array-like subscript operation to get the character at a specified position in the string


var s = 'Hello, world!';

s[0]; // 'H'

s[6]; // ' '

s[12];    // '!'

s[13];    // undefined  Indexes that are out of range do not report errors, but 1 Rhythm return undefined

 It is important to note that strings are immutable, and if you assign a value to an index of a string, there will be no error, but there will be no effect: 

var s = 'Test';

s[0] = 'X';

alert(s);  // s Is still 'Test'

8-Upper and Lowercase


var s = 'Hello';

s.toUpperCase();  //  Return 'HELLO'

    

var s = 'Hello';

s.toLowerCase();  //  Return 'hello'

9-Searches for the location where the specified string occurs


var s = 'hello, world';

s.indexOf('world'); //  Return 7

s.indexOf('World'); //  The specified substring was not found, returning -1

10-Gets the substring of the specified index interval of the string


function sum(i1,i2){return i1+i2}
0

The object of 11-JavaScript is an unordered collection data type, which consists of several key-value pairs


function sum(i1,i2){return i1+i2}
1

12-To detect whether xiaoming has a 1 attribute, use the in operator:


function sum(i1,i2){return i1+i2}
2

13-Map


var m = new Map([['Michael', 95], ['Bob', 75], ['Tracy', 85]]);//2 Dimensional array initialization method 

m.get('Michael'); // 95

 

var m = new Map();//  Direct initialization 1 Empty Map

m.set('Adam', 67); //  Add a new key-value

m.set('Bob', 59);

m.has('Adam');    //  Does it exist key 'Adam': true

m.get('Adam');    // 67

m.delete('Adam'); //  Delete key 'Adam'

m.get('Adam');    // undefined

 

var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]);

for (var n of m) {   //  Traversal Map

 alert(n[1] + '=' + n[0]);

}

14-The built-in forEach method of iterable, which accepts a function and automatically calls it back every iteration.


function sum(i1,i2){return i1+i2}
4

15-Using the map () method of Array, passing in our own function, we get a new Array as the result:


function sum(i1,i2){return i1+i2}
5

16-Use map () to convert all the numbers of Array to strings:


function sum(i1,i2){return i1+i2}
6

17-Use reduce () of Array for cumulative calculation


function sum(i1,i2){return i1+i2}
7

18-Make a great conversion with reduce (): convert [1, 2, 5, 8, 0] to an integer of 12580


var arr = [1, 2, 5, 8, 0];

alert(arr.reduce(function(x,y){

return x*10+y;

}));

19-Filter out some elements of Array with filter ()


function sum(i1,i2){return i1+i2}
9

By default, the sort () method of 20-Array converts all elements to String and then sorts them, so...


[10, 20, 1, 2].sort(); // [1, 10, 2, 20]

 So if you want to sort by number size, you can write this: 

var arr = [];

for (var x = 1; x <= 10; x++) {

 arr.push(x);

}

document.write(arr+"<br/>");

document.write(arr.sort(function(x,y){

return x<y?true:false;

}));

 

 To ignore the influence of letter case, you must first convert to uppercase or lowercase 


var arr = ['Google', 'apple', 'Microsoft'];

alert(arr.sort(function (s1, s2) {

 var x1 = s1.toUpperCase();

 var x2 = s2.toUpperCase();

 return x1 < x2 ?false:true;

})); // ['apple', 'Google', 'Microsoft']

21-closure (Closure) program structure


 Assign the function as a return value to the parameter, and call the parameter to obtain the calculation result 


var arr = [];

for(var n=1;n<101;n++){

arr.push(n);

}

function lazy_sum(arr){

 var sum = function(){

 return arr.reduce(function(x,y){

 return x+y;

 });

 }

 return sum;

}

var f = lazy_sum(arr);

alert(f());

    

 The returned function is not executed immediately, but until the f() Before executing 


function count() {

 var arr = [];

 for (var i=1; i<=3; i++) {

 arr.push(function () {

 return i * i;

 });

 }

 return arr;

}

var results = count(); //results It's stored in 3 A function

var f1 = results[0];

var f2 = results[1];

var f3 = results[2];

    

f1(); // 16  The returned function references a variable i But it is not executed immediately. 

f2(); // 16  Wait until 3 When all functions return, the variables they reference i Has become 4 , 

f3(); // 16  So the final result is 16

*** Remember when returning closures: The return function should not refer to any loop variables or variables that will change later !

 

 ③ If 1 What if you have to reference a loop variable? 

  By recreating the 1 Function that binds the current value of the loop variable with its parameters, 

  No matter how the loop variable changes later, the value bound to the function parameter remains unchanged: 


function count() {

 var arr = [];

 for (var i=1; i<=3; i++) {

 arr.push(function(n){

 return function(){

 return n*n;

 }

 }(i));

 }

 return arr;

}

 

var results = count();

var f1 = results[0];

var f2 = results[1];

var f3 = results[2];

 

alert(f1()); // 1

alert(f2()); // 4

alert(f3()); // 9

 

 ④ In the absence class Mechanism, only function language, with the help of closures, can encapsulate 1 Private variables 


function creat_counter(init){

 var n = init||0;

 return{

 add:function(){

 n+=1;

 return n;

 }

 }

}

    

var c = creat_counter();

alert(c.add());//1

alert(c.add());//2

alert(c.add());//3

*** In the returned object, the 1 Closure that carries local variables n And, variables cannot be accessed at all from external code n . 

 In other words, a closure is a function that carries state, and its state can be completely hidden from the outside world. 

 

 ⑤ Utilization Math.pow(x, y) Calculation x^2 Or x^3 //Math.pow(x, y)-->x^y


function make_pow(y){

 return function(x){

 return Math.pow(x,y);

 }

}

    

var pow2 = make_pow(2)

var pow3 = make_pow(3)

    

alert(pow2(3))//9

alert(pow3(3))//27

22-Arrow function (currently only supported by firefox)//Parameter = > Function body


var f = x => x*x*x

alert(f(3)) //27

23-Generation of Fibonacci Sequence with generator


var f=function(i1,i2){return i1+i2;}; alert(f(1,2));// Ordinary anonymous function 

alert(function(i1,i2){return i1+i2;}(3,4));// Direct declaration , Use immediately 
3

Related articles: