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 zero1-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));//Directly declare, use immediately3-JS does not have a concept of class, so some methods look like classes
function Person(name,age){this.Name=name;//Dynamicly add attributes, similar to dynamic A in C#. 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(); //Call p1.Gender='Male' like a class; //Dynamicly add the 'gender' attribute alert(p1.Gender);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<=arr.length-1;i++){alert(arr[i]);}5-Array is an array, also a Dictionary, and also a Stack
var dict=new Array();//As Dictionary, use dict['I']='wo';dict['love']='ai';dict['you']='ni';alert(dict['I']); //Call alert(dict.love); //Call like calling attributes (characteristics of dynamic language) for(var k in dict){ //Travel alert(k); //'I', 'love', 'you'-->Print out key}for(var k of dict){ //Travel alert(k); //'wo', 'ai', 'ni'-->Print out value}var arr = [1,2,3,4,5];//Simplified creation method of Array var arr = {"lorry":21,"cloud":20};//Dictionary style creation method6-Transfer all elements that can be called on the current page
var s=null;for(var k in document){//The properties of the object are 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 outside the range will not report an error, but they will always return undefined. It should be noted that the string is immutable. If you assign a value to a certain index of the string, there will be no errors, but there is no effect: var s = 'Test';s[0] = 'X';alert(s); // s is still 'Test'
8-Capsule lowercase
var s = 'Hello';s.toUpperCase(); // Return 'HELLO' var s = 'Hello';s.toLowerCase(); // Return 'hello'
9-Search for the location where the specified string appears
var s = 'hello, world';s.indexOf('world'); // Return 7s.indexOf('World'); // No specified substring was found, return -110-Get substrings of string specified index interval
var s = 'hello, world's.substring(0, 5); // Start from index 0 to 5 (excluding 5), return 'hello's.substring(7); // Start 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: 'Xiaoming', 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 ','};xiaoming.name; // 'Xiaoming'xiaoming.birth; // 1990 access to the attribute is done through the . operator, but this requires that the attribute name must be a valid variable name. If the attribute name contains special characters, it must be enclosed with []: var xiaohong = { name: 'Xiaohong', 'middle-school': 'No.1 Middle School'};xiaohong['middle-school']; // 'No.1 Middle School'xiaohong['name']; // 'Xiaohong'xiaohong.name; // 'Xiaohong'xiaohong.age; // undefined12-To detect whether xiaoming has a certain attribute, use the in operator:
'name' in xiaoming;// true'grade' in xiaoming;// false***If in determines that a property exists, this property may not be xiaoming, it may be inherited by xiaoming: 'toString' in xiaoming; // true***To determine whether a property is owned by xiaoming itself, not inherited, you can use hasOwnProperty() method: xiaoming.hasOwnProperty('name'); // truexiaoming.hasOwnProperty('toString'); // false13-Map
var m = new Map([['Michael', 95], ['Bob', 75], ['Tracy', 85]]);// 2D array initialization method m.get('Michael'); // 95 var m = new Map();// Directly initialize an empty Mapm.set('Adam', 67); // Add a new key-valuem.set('Bob', 59); m.has('Adam'); // Whether key 'Adam': truem.get('Adam'); // 67m.delete('Adam'); // Delete key 'Adam'm.get('Adam'); // undefined var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]);for (var n of m) { // traverse 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'];a.forEach(function (element, index, array) { // element: point to the value of the current element // index: point to the current index // array: point to the Array object itself alert(element);}); Set is similar to Array, but Set does not have an index, so the callback function has a maximum of two parameters: var s = new Set(['A', 'B', 'C']); s.forEach(function (element, set) { alert(element);}); Map's callback function parameters are value, key and map itself: var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]);m.forEach(function (value, key, map) { alert(value);}); var a = ['A', 'B', 'C'];a.forEach(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];arr.map(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];arr.map(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 <= 100; x++) { arr.push(x); //Put 1~100 into an array}alert(arr.reduce(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(arr.reduce(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(arr.filter(function(x){return x%2===0;}));//0,2,4,6,8 // Return true, keep deletion of the empty string in an Array var arr = ['A', '', 'B', null, undefined, 'C', ' '];alert(arr.filter(function (s) { return s && s.trim(); // Note: There is no trim() method in 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, 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 letters, 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 program structure
① Assign the function as the return value to the parameter, 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 does not execute until f() is called function count() { var arr = []; for (var i=1; i<=3; i++) { arr.push(function () { return i * i; }); } return arr;}var results = count(); //There are 3 functionsvar 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 three functions return, the variable i referenced has become 4, f3(); // 16 Therefore, the final result is 16***When returning the closure, remember: do not refer to any loop variables, or variables that will change in the future! ③What if you must refer to loop variables? The method is to create another function and use the parameters of the function to bind the current value of the loop variable. Regardless of how the loop variable changes in the subsequent time, 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()); // 1alert(f2()); // 4alert(f3()); // 9 ④ In languages without class mechanism and only function, with the help of closures, a private variable can be encapsulated function creat_counter(init){ var n = init||0; return{ add:function(){ n+=1; return n; } }} var c = creat_counter();alert(c.add());//1alert(c.add());//2alert(c.add());//3*** In the returned object, a closure is implemented, which carries the local variable n, and the variable n cannot be accessed from external code at all. In other words, a closure is a function that carries states, and its state can be completely hidden from the outside. ⑤ Use Math.pow(x, y) to calculate x^2 or x^3 //Math.pow(x, y)-->x^yfunction make_pow(y){ return function(x){ return Math.pow(x, y); }} var pow2 = make_pow(2)var pow3 = make_pow(3) alert(pow2(3))//9alert(pow3(3))//2722-Arrow function (currently only supported by firefox) //parameters => Function body
var f = x => x*xxxalert(f(3)) //27
23-Generator to generate Fibonacci sequences
function* fib(max){ var t,a=0,b=1,n=1; while(n<=max){ yield a; t=a+b; a = b; b = t; n++; } return a;}for (var x of fib(10)) {//Iterate the generator object document.write(x+' '); // Output 0, 1, 1, 2, 3} Use generator to generate a self-incremental ID (no global variable required) function* next_id(){for(var x = 1; x < 100; yield x++ );}var g = next_id();alert(g.next().value);//1alert(g.next().value);//2alert(g.next().value);//3The above is the full content of the JavaScript self-study notes (must-read article) brought to you by the editor. I hope everyone will support Wulin.com more~