SoFunction
Updated on 2025-04-10

JavaScript self-study notes (must read)

0-Judge 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-Declaration function does not require declaration of return value or parameter type, and the end of the sentence does not even require ';'

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

2-Directly declare anonymous functions to use 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));//Declare directly, use immediately

3-JS does not have a concept of class, so some methods look like classes

function Person(name,age){

=name;// Dynamically add attributes, similar to Cdynamic A in # = new ExpendoObject();=age;

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

}

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

(); //Call like a class
='male';    // Dynamically add 'gender' attribute
alert();

4-Array objects are arrays, and you do not need to pre-qualify the length of the array.

var arr=new Array();

arr[0]=0;

arr[1]=1;

arr[2]=2;

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

alert(arr[i]);

}

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

var dict=new Array();//Use as Dictionary
dict['I']='wo';

dict['like']='ai';

dict['you']='ni';

alert(dict['I']); //Call through key value
alert(dict.like); //Call like calling properties (the characteristic of dynamic language)
 

for(var k in dict){ //Travel in js
 alert(k);  //'I', 'love', 'you'-->what prints out is the key
}

for(var k of dict){ //Travel in js
 alert(k);  //'wo', 'ai', 'ni'-->The printed value is
}

var arr = [1,2,3,4,5];//Simplified creation of Array
var arr = {"lorry":21,"cloud":20};//How to create dictionary style

6-Transfer all elements that can be called on the current page

var s=null;

for(var k in document){//The properties of the object appear in the form of a key
 s+=k+" ;";

}

alert(s);

7-Use subscript operations similar to Array to obtain characters at a specified position of the string

var s = 'Hello, world!';

s[0]; // 'H'

s[6]; // ' '

s[12];    // '!'

s[13];    // undefined indexes that are out of range will not report an error, but will return undefined
It is important to pay special attention to,Strings are immutable,If you assign a value to an index of a string,There will be no errors,but,No effect either:

var s = 'Test';

s[0] = 'X';

alert(s);  // sStill for'Test'

8-Capsule lowercase

var s = 'Hello';

();  // Return to 'HELLO'
    

var s = 'Hello';

();  // return'hello'

9-Search for the location where the specified string appears

var s = 'hello, world';

('world'); // Return to 7
('World'); // No specified substring was found, return -1

10-Get substrings of string specified index interval

var s = 'hello, world'

(0, 5);  // Start from index 0 to 5 (excluding 5), return 'hello'
(7);// From index 7 to end, return 'world'

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

var xiaoming = {

 name: 'Xiao Ming',

 birth: 1990,

 school: 'No.1 Middle School',

 height: 1.70,

 weight: 65,

 score: null//The last key-value pair does not need to be added ',' at the end
};

;   // 'Xiao Ming'
;    // 1990

Access properties is through.Operator completed,But this requires that the attribute name must be a valid variable name。If the attribute name contains special characters,It must be used[]Cover it up:


var xiaohong = {

  name: 'Little Red',

  'middle-school': 'No.1 Middle School'

};

xiaohong['middle-school'];   // 'No.1 Middle School'

xiaohong['name'];  // 'Little Red'
;    // 'Little Red'
; // undefined

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

'name' in xiaoming;// true

'grade' in xiaoming;// false

***ifinDetermine that an attribute exists,This attribute does not necessarily meanxiaomingof,It may bexiaoming继承得到of:


'toString' in xiaoming;   // true

***To determine whether an attribute isxiaoming自身拥有of,而不是继承得到of,Can be usedhasOwnProperty()method:


('name');    // true

('toString'); // false

13-Map

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

 

var m = new Map();// Directly initialize an empty map
('Adam', 67); // Add a new key-value
('Bob', 59);

('Adam');    // Is there a key 'Adam': true
('Adam');    // 67

('Adam'); // Delete key 'Adam'
('Adam');    // undefined

 

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

for (var n of m) {   // traverse the map
 alert(n[1] + '=' + n[0]);

}

14-iterable built-in forEach method, which receives a function and automatically calls back each iteration.

var a = ['A', 'B', 'C'];

(function (element, index, array) {

 // element: Point to the current element value
 // index: Point to the current index
 // array: Point to the Array object itself
 alert(element);

});

    

SetandArraysimilar,butSetNo index,Therefore, the callback function has up to two parameters:


var s = new Set(['A', 'B', 'C']);

(function (element, set) {

 alert(element);

});

 

MapThe callback function parameters arevalue、keyandmapitself:


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

(function (value, key, map) {

 alert(value);

});

    

var a = ['A', 'B', 'C'];

(function (element) {

 alert(element);

});

15-Use Array's map() method, pass in our own function, and you get a new Array as the result:

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

(function(x){

return x*x;

}).forEach(function (element) {

alert(element);// [1, 4, 9, 16, 25, 36, 49, 64, 81]

});

16-Use map() to convert all numbers in Array into strings:

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

(String); // ['1', '2', '3', '4', '5', '6', '7', '8', '9']

17-Use Array's reduce() to do cumulative calculations

var arr = [];

for (var x = 1; x &lt;= 100; x++) {

 (x); //Put 1~100 into the array
}

alert((function(x,y){

return x+y;   //Cumulative sum of all objects of arr, return the sum result
}));

18-Use reduce() to make awesome conversion: convert [1, 2, 5, 8, 0] into integer 12580

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

alert((function(x,y){

return x*10+y;

}));

19-Use filter() to filter out certain elements of Array

var arr = [0,1,2,3,4,5,6,7,8,9];

alert((function(x){

return x%2===0;

}));//0,2,4,6,8 //Return true and reserved
    

Put oneArrayDelete the empty string in

var arr = ['A', '', 'B', null, undefined, 'C', ' '];

alert((function (s) {

 return s &amp;&amp; (); // Note: There is no trim() method for versions below IE9
})); // ['A', 'B', 'C']

20-Array's sort() method converts all elements into String first and then sorts it, so...

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

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

var arr = [];

for (var x = 1; x &lt;= 10; x++) {

 (x);

}

(arr+"&lt;br/&gt;");

((function(x,y){

return x&lt;y?true:false;

}));

 

To ignore the case effect of letters,Convert to uppercase or lowercase first


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

alert((function (s1, s2) {

 var x1 = ();

 var x2 = ();

 return x1 &lt; x2 ?false:true;

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

21-Closure program structure

 

①Assign a function as a return value to a parameter,Call this parameter to obtain the calculation result


var arr = [];

for(var n=1;n&lt;101;n++){

(n);

}

function lazy_sum(arr){

 var sum = function(){

 return (function(x,y){

 return x+y;

 });

 }

 return sum;

}

var f = lazy_sum(arr);

alert(f());

    

②The returned function is not executed immediately,But until it is calledf()Only execute


function count() {

 var arr = [];

 for (var i=1; i&lt;=3; i++) {

 (function () {

 return i * i;

 });

 }

 return arr;

}

var results = count(); //There are 3 functions stored in the results
var f1 = results[0];

var f2 = results[1];

var f3 = results[2];

    

f1(); // 16 The returned function refers to the variable i, but it is not executed immediately.
f2(); // 16 When all 3 functions return, the variable i referenced has become 4.
f3(); // 16 So the final result is 16
***Remember when returning to the closure:Return function does not refer to any loop variables,Or variables that will change later!

 

③What to do if you have to refer to loop variables?

 The method is to create another function,Use the parameters of this function to bind the current value of the loop variable,

 Regardless of how the loop variable is subsequently changed,The value bound to the function parameter remains unchanged:


function count() {

 var arr = [];

 for (var i=1; i&lt;=3; i++) {

 (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 noclassmechanism,Only in the language of functions,With the help of closure,Can encapsulate a private variable


function creat_counter(init){

 var n = init||0;

 return{

 add:function(){

 n+=1;

 return n;

 }

 }

}

    

var c = creat_counter();

alert(());//1

alert(());//2

alert(());//3

***In the returned object,Implemented a closure,The closure carries local variablesn,and,Variables are simply inaccessible from external coden。

in other words,Closure is a function that carries state,and它的状态可以完全对外隐藏起来。

 

⑤use(x, y)calculatex^2orx^3 //(x, y)--&gt;x^y


function make_pow(y){

 return function(x){

 return (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) //parameters => Function body

var f = x => x*x*x

alert(f(3)) //27

23-Generator to generate Fibonacci sequences

function* fib(max){

 var t,a=0,b=1,n=1;

 while(n&lt;=max){

 yield a;

 t=a+b;

 a = b;

 b = t;

 n++;

 }

 return a;

}

for (var x of fib(10)) {//Iterate the generator object with for ... of loop
  (x+'&amp;nbsp'); // Output 0, 1, 1, 2, 3 in turn
}

 

usegeneratorGenerates an autoincrementID(No global variables required)

function* next_id(){

for(var x = 1; x &lt; 100; yield x++ );

}

var g = next_id();

alert(().value);//1

alert(().value);//2

alert(().value);//3

The above is the full content of the JavaScript self-study notes (must-read article) brought to you by the editor. I hope everyone supports me~