1. Finding Scope
Where the current function is defined, its superior scope is who, and it has nothing to do with where the function is executed.
//Scope examples var num = 12; function fn(){ var num = 120; return function(){ console.log(num); } } var f = fn(); f();//->120 (function(){ var num = 1200; f();//->120 }())
The difference between + + i and i +
//Examples var i = 5; 5 + i++ //->10 //i + + is to first calculate i itself plus 1 //======== var j = 5; 5 + (++j) //->11 //+ + j is itself added 1 before operation //Interview questions var n = 2; var num = 5 + (++n) + (n++) + (n++) + (++n); // - > 21
3. Pre-interpretation
Before js is executed, the browser's home page will pre-declare or define the keywords with VaR and function; var (just pre-declare) function (pre-declare + definition)
Note: There is a difference between defining a num = 10 (without var) and VaR in global scope
//Examples console.log(num);//->undefined console.log(num1);//->num1 is not defined var num = 10;//-> Pre-explanation - > window. num = 10 num1 = 10;//->window.num1 = 10 //num1 without var has not been declared in advance, so it is not defined.
Explain interview questions in advance
//Example 1 function a(b){ alert(b); function b(){ alert(b); } b(); } a(1); //1 - > alert (b function), 2 - > alert (function) //Example 2 alert(a); //undefined var a = 0; alert(a); //0 function fn(){ alert(a); //0; because there is no var, so a here will be regarded as global, look up, find a=0, so it is 0, if there is no global, there will be an error. a = 2; alert(a); //2 } fn() alert(a); //2. FN modifies this global a //Example 3 <script> alert(a);//Error reporting, because encounter < script > tag pair, will first pre-parse this piece, run to the following before pre-parsing, there is no pre-parsing below, so can not find a, so the error reporting </script> <script> alert(a); //undefined var a = 0; alert(a); //0 </script>
4. Distinguish this
Function execution, first of all, depends on whether the name of the function has "...", and if so, who is this before "...", and if not, this is window.
this of the self-executing function is always window
To bind an event to an element, when the event triggers, the corresponding method is executed. this is the current element in the method.
This in the constructor is an example of this class
this can also be changed by call, apply, and bind
function fn(){ console.log(this); } var obj = { name:"Li Si", writeJs:fn } obj.writeJs();//this->obj var fn = obj.writeJs; fn();//this->window function sum() { fn();//this->window } sum(); (function() { fn();//this->window )() document.getElementById('div').onclick = fn;//this->#div document.getElementById('div').onclick = function() { //this->#div fn();//this->window }
this Comprehensive Example (360 Interview Questions)
var num = 20; var obj = { num: 30, fn: (function (num) { this.num *= 3; num += 15; var num = 45; return function () { this.num *= 4; num += 20; console.log(num); } }) (num) } var fn = obj.fn; fn();//65 obj.fn();//85
5. Singleton Model
The attributes and methods of describing the same thing (the same object) are placed in a memory space and play the role of grouping, so that the attribute names of different things are the same and there will be no conflict with each other. We call this grouping coding mode "singleton mode";
var obj = { name: 'Zhang San', age: '18', writeJs: function(){ console.log('my is '+this.name+' can write js'); } } obj.writeJs();
Note: obj is also called "namespace". Singleton mode is often used in project development. We can use singleton mode for modular development.
6. Factory Model
Although the singleton mode can solve the grouping function, it can not realize mass production, which belongs to manual operation mode.
Factory Mode - > "Function Encapsulation" and "Low Coupling and High Cohesion": Reducing Redundant Code in Pages and Improving Code Reuse
function createJs(name,age){ var obj = {}; obj.name = name; obj.age = age; obj.writeJs = function(){ console.log('my is '+ this.name +' can write js'); } return obj; } var zhangsan = createJs('Zhang San','18'); zhangsan.writeJs();
All programming languages are object-oriented. There are inheritance, encapsulation, polymorphism of classes
Inheritance: Subclasses inherit attributes and methods of parent classes
Packaging: Correspondence Packaging
Polymorphism: Multiple Forms of Current Methods
Polymorphism in background language includes overloading and rewriting. There is no overload for polymorphism in js. The method name is the same. The preceding method will be covered by the latter one, and only one method will be retained at last. (There is a similar overload but not overload in js: different functions can be implemented depending on the parameters passed.) Rewrite: The method of subclasses rewriting parent classes
7. Constructor pattern
The constructor creates an instance through the new keyword.
var ex = new CreateJs(); where ex is an instance of CreateJs, generating the CreateJs class;All classes in Js are function data types, which are changed into a class by new execution, but it is also a normal function itself.
All instances in Js are object data types
In the constructor pattern, this.xxx=xxx in the class is an instance of the current class
Different methods exist between different instances (the following example)
-
In constructor mode, the browser will return our instance by default (returning the value of the object data type); if we write return manually;
If ruturn is a value of a basic data type, the current instance remains unchanged, for example: return 10;
If return is a value that refers to a data type, the current instance will be replaced by the value it returns, such as ruturn {name: "Zhang San"}
-
Check whether an instance belongs to this class instanceof;
zhangsan instancaof CreateJs->true
In: To detect whether an attribute belongs to this object attr in object, whether private or common, in detection is true as long as it exists
HasOwnProperty: Used to detect whether an attribute is a private attribute of the object, this method can only detect the private attribute obj.hasOwnProperty(attr);
function CreateJs(name,age) { this.name = name; this.age = age; this.writeJs = function() { console.log('my is '+ this.name +' can write js'); } } var zhangsan = new CreateJs('Zhang San','18'); zhangsan.writeJs(); var lisi = new CreateJs('Li Si','20'); lisi.writeJs(); zhangsan.writeJs === lisi.writeJs//false
8. Prototype Chain Model
Each function data type (ordinary functions, classes) has a inherent property: prototype (prototype), and this property is the value of an object data type;
The browser on prototype naturally adds an attribute constructor (constructor) to it. The attribute value is the current function (class) itself.
Each object data type (common object, instance, prototype.) is born with an attribute _proto_ whose value is the prototype of the class to which the current instance belongs.
Object is the base class of all objects in Js. There is no _proto_ attribute on Object.prototype.
function CreateJs(name,age) { this.name = name; this.age = age; } CreateJs.prototype.writeJs = function() { console.log('my is '+ this.name +' can write js'); } var zhangsan = new CreateJs('Zhang San','18'); zhangsan.writeJs(); var lisi = new CreateJs('Li Si','20'); lisi.writeJs(); zhangsan.writeJs === lisi.writeJs//true
When the attribute value is obtained by the object name and attribute name, the private attribute value is first found in the object, if the private attribute exists, then the private attribute value is obtained.
If private or not, the prototype of the class belongs to is found through _proto_. If the prototype exists, the public attribute values are obtained.
If not on the prototype, continue to look up through _proto_ on the prototype until Object. prototype is found.
9. call, apply, bind use
The Difference between call and apply
For application and call, the effect is exactly the same, but the way to accept parameters is not the same.
func.call(this, arg1, arg2); func.apply(this, [arg1, arg2])
Example:
//1. Addition between arrays var array1 = [12 , "foo" , {name "Joe"} , -2458]; var array2 = ["Doe" , 555 , 100]; Array.prototype.push.apply(array1, array2); /* array1 The values are [12,'foo,'{name,'Joe'}, -2458,'Doe,'555, 100] */ //2. Get the maximum and minimum values in the array (there is no max method in the array itself) var numbers = [5, 458 , 120 , -215 ]; var maxInNumbers = Math.max.apply(Math, numbers), //458 maxInNumbers = Math.max.call(Math,5, 458 , 120 , -215); //458 //3. Test data type Object.prototype.toString.call(obj) === '[object Array]' ; //4. Class Array to Array var domNodes = Array.prototype.slice.call(document.getElementsByTagName("*"));
bind
The bind() method creates a new function, called a binding function. When the binding function is called, the binding function takes the first parameter of the bind() method as this when it is created, the second and subsequent parameters of the bind() method as this, and the parameters of the binding function itself as the original function when it runs. Parameters to call the original function
var bar = function(){ console.log(this.x); } var foo = { x:3 } bar(); // undefined //bind binds this and parameters first, without executing its own functions //call and apply are functions that execute immediately after binding this and parameters var func = bar.bind(foo); func(); // 3
10. Calculate the maximum value in an array
<!--1,Sorting method--> var arr = [12,43,2323,455,23,5]; arr.sort(function(x,y) { return x-y; }) var max = arr[arr.length-1]; <!--2,Hypothesis method--> var arr1 = [123,34,54,23,56,1]; var max = arr1[0]; for(var i = 0;i < arr1.length;i++ ) { var cur = arr1[i]; if(cur>max) { max = cur[i]; } } <!--3,Math.max + apply method--> var arr2 = [23,43,123,341,3233]; var max = Math.max.apply(null,arr2); <!--4,Math.max + eval method--> var arr3 = [567,23,42,45,1,98]; var max = eval("Math.max("+arrr.toString()+")");
11. Average Array
<!--1,Class Array to Array--> function avgFn() { var arr = Array.prototype.slice.apply(arguments); arr.sort(function(x,y) { return x - y; }) arr.shift() arr.pop(); var arg =(eval(arr.join("+"))/arr.length).toFixed(2) return arg; } avgFn(68,97,97,91,99.1,89.5,98.23) <!--2,With the help of call--> function avgFn() { var arr = [].sort.call(arguments,function(x,y) { return x-y; }); [].shift.call(arguments); [].pop.call(arguments); return (eval([].join.call(arguments,"+"))/arguments.length).toFixed(2); } avgFn(68,97,97,91,99.1,89.5,98.23)
12. The Deepening of sort
arr.sort(); can only be sorted by default by numbers less than 10 and by 26 letters
var arr = [1,3,4,65,23,32,43,567]; arr.sort();//log->[1, 23, 3, 32, 4, 43, 567, 65] var arr1 = [2,5,6,4,9,1.2,0.9]; arr1.sort();//log->[0.9, 1.2, 2, 4, 5, 6, 9] var arr2 = ['a','y','b','t','p','c']; arr2.sort();//log->["a", "b", "c", "p", "t", "y"]
arr.sort(function() {}) transfer parameter
<!--Ascending order--> var arr = [1,3,4,65,23,32,43,567]; arr.sort(); /** *Values of a and b in execution *a b *1 3 *3 4 *4 65 *65 23 *4 23 *65 32 *23 32 *65 43 *32 43 *65 567 *a - b > 0 a Change position with b *a - b <= 0 Location unchanged */ arr.sort(function(a,b){ return a - b; }) <!--Descending order--> arr.sort(function(a,b){ return b - a; })
Using localeCompare alphabetical sorting
localeCompare's first string letters are sorted by 26 letters. If the first letters are the same, they are sorted by the second letter, and so on. Chinese characters are first converted to Pinyin and then sorted. If Chinese homonyms are sorted by unicode, Chinese characters are sorted by unicode.
'a'.localeCompare('b') //-1 'c'.localeCompare('b') //1 var arr = [{name:"wangwu",age:17},{name:"lisi",age:17},{name:"dahuang",age:21}]; arr.sort(function(a,b){ return a.name.localeCompare(b.name); }) //[{name:"dahuang",age:21},{name:"lisi",age:17},{name:"wangwu",age:17}] var arr = [{name:"xiao lu",age:17},{name:"Lao Wang",age:17},{name:"Chinese rhubarb",age:21}]; arr.sort(function(a,b){ return a.name.localeCompare(b.name); }) //[{name: rhubarb, age:21},{name: Lao Wang, age:17},{name: Xiao Lu, age:17}]
13. DOM reflow, DOM redraw, DOM mapping
DOM reflow: After rendering the DOM tree, as long as the HTML structure of the page changes (adding deleted elements, changing location), the browser has to recalculate the latest DOM structure and re-render the current page.
DOM redrawing: DOM tree position does not change, if the color background of the element changes, it will only be rendered for this element, not the entire page.
DOM mapping: Labels in pages are tightly bound to elements objects (element sets) retrieved in Js. HTML structure in pages has changed, Js does not need to retrieve, and the contents of collections will change automatically.
14. The Method of Data Binding in js
1. Dynamic Node Creation
var oUl = document.getElementById('ul'); var oLi = document.createElement('li'); oLi.innerHTML = "hello world"; oUl.appendChild(oLi);
2. The way of string splicing
var oUl = document.getElementById('ul'); var str = ''; for(var i = 0;i < arr.length; i++) { str += "<li>"; str += "hello" + arr[i]; str += "</li>" } oUl.innerHTML += str;
3. Document fragmentation
var oUl = document.getElementById('ul'); var frg = document.createDocumentFragment();//Create a document fragment var oLi = document.createElement('li'); oLi.innerHTML = "hello world"; frg.appendChild(oLi); oUl.appendChild(frg); frg = null;//Manual clearance of debris
15. Regularity
What is a rule?
It's a rule that handles strings.
-
The Creation of Regularity
Literal Quantity Creation
var reg = /\d/;
2. Instance creation
var reg = new RegExp("\d");
Metacharacters
Every regular expression consists of metacharacters and modifiers
-
Metacharacters with special meaning
==\ The meaning represented by the character after escape== ==^ Start with a metacharacter== == $: Ends with a metacharacter== ==\ n: Match a newline character== ==...: Any character except \n== == (ii) Grouping== == One of X | y: X or y== == [x y z]: Any character in X or Y or z== == [a-z]: Any character between a-z== == [^a-z]: Any character except a-z== ==\ d: Any number between 0 and 9== ==\ b: Match a boundary character== ==\ w: Any character in the underscore of a numeric letter== ==\ s: Matches a blank character space, tab, page break...==
-
Quantifier characters representing occurrences
==* 0 to many times== ==+ One or more times== == Does it occur 0 to 1 time?== == {n}: n times== == {n,}: n to multiple occurrences== == {n,m}: n to m occurrences==
() The role of grouping
Change the priority of x|y
var reg = /^18|19$/; //18,19,181,189,119,819,1819....true var reg = /^(18|19)$/; //18,19true
Grouping Reference
var reg = /^(\w)\1(\w)\2$/; reg.test("aabb")//true reg.test("abcd")//false //\ 1 Represents exactly the same content as the first group //\ 2 Represents exactly the same content as the second group //Remove duplicate characters var str = 'aaaabbbbccccddddddssss440000008888'; str.replace(/(\w)\1+/g,"$1"); //"abcds408"
Packet capture
When capturing regularities, not only large regularities can be matched, but also small groupings can be captured.
var reg = /^(\d{2})(\d{4})(\d{4})(\d{4})\d{2}(\d{1})[\d|X]$/ var arr = reg.exec('340604198802112411'); //["340604198802112411", "34", "0604", "1988", "0211", "1"] //Contents of 340604198802112411 Grand Regular Matching //"34", "0604", "1988", "0211", "1" small group matching
[] (1), all characters appearing in the middle brackets are characters representing their own meaning (without special meaning) (2), and the middle brackets do not recognize double digits.
var reg = /^[.]$/; reg.test('1');//false reg.test('.');//true var reg = /[12]/; //1 | | 2 is not 12 var reg = /^[21-57]$/; //Any one of 2 | | 1-5 | | 7
//Age between [16-58] var reg = /^(1[6-9]|[2-4]\d|5[0-8])$/; //Simple Verification Mailbox var reg = /^[\w.-]+@[\da-zA-Z]+(\.[a-zA-Z]{2,4}){1,2}$/; //Chinese Standard Real Name 2-4 Bit Chinese Characters var reg = /^[\u4e00-\u9fa5]{2,4}$/; //ID card No. //340604198802112411 //34 (Provincial) 0604 (Urban County) 19880211 (Birth Year) 24 (useless) 1 (odd male, even female) 1(0-9||X) var reg = /^(\d{2})(\d{4})(\d{4})(\d{4})\d{2}(\d{1})[\d|X]$/;
Regular capture exec
The captured content is an array
var reg = /\d+/; reg.exec('ducen23niubi21'); //0:"23",index:5,input:"ducen23niubi"
Characteristics of Regular Capture
Lazy: Every execution of exec captures only the first matched content, and without any processing, multiple acquisitions are performed, capturing the first matched value.
var reg = /\d+/ reg.lastIndex//0 res = reg.exec('ducen23niubi12')//["23"] reg.lastIndex//0 res = reg.exec('ducen23niubi12')//["23"]
//To solve laziness, add a modifier g after the regular var reg = /\d+/g reg.lastIndex//0 res = reg.exec('ducen23niubi12')//["23"] reg.lastIndex//7 res = reg.exec('ducen23niubi12')//["12"] reg.lastIndex//14 res = reg.exec('ducen23niubi12')//null
Greed: Regularly, each capture is based on the longest matching result
var reg = /\d+/; res = reg.exec('ducen2017niubi12'); //The catch is ["2017"] not 2 //Solve the greed of regularity (add a quantifier character after the quantifier character? ) var reg = /\d+?/; res = reg.exec('ducen2017niubi12'); //The catch is ["2"];
++ There are many roles in regularization. Placing a different meta-character after it represents 0-1/d?/(number appears once or does not appear); placing a quantifier after the meta-character is the greedy ++ to cancel capture.
5. Regular modifiers (g, i, m)
var reg = /\d/gim //g: Global Matching //i: Ignore case matching //m: Multi-line matching
var reg = /\d+/g var arr = [] res = reg.exec('ducen23niubi12'); while(res) { arr.push(res[0]); res = reg.exec('ducen23niubi12') } arr//["23", "12"]
6. The match ing method in strings
Get all regular matching characters
var reg = /\d+/g var arr = 'ducen23niubi12'.match(reg); arr//["23", "12"]
Although matching is simpler than our exec in the current situation, there are some problems that matching can't handle by itself: in the case of group capture, matching can only capture the content of large regular matching, but can't capture the content of small regular matching.
7. replace method in strings
var str = "ducen2015ducen2016"; str.replace('ducen','huming'); //"huming2015ducen2016" str.replace(/ducen/g,function(arg){ console.log(arguments); <!--Execution twice ["ducen", 0, "ducen2015ducen2016"] ["ducen", 9, "ducen2015ducen2016"] --> return 'huming'; }) //"huming2015huming2016" str.replace(/ducen(\d+)/g,function(arg){ console.log(arguments) console.log(arguments[1])//Acquisition of minor rules in 2015 and 2016 }) <!--["ducen2015", "2015", 0, "ducen2015ducen2016"]--> <!--["ducen2016", "2016", 9, "ducen2015ducen2016"]-->
The number of executions of anonymous functions in replace depends on the number of regular captures
Every time we execute an anonymous function, the passed parameter values arguments are very similar to the results we captured by ourselves through exec (even if there are regular groupings, we can get them through arguments)
Return: What is the result of your return, which is equivalent to replacing the content captured by the current big rule with the content returned?
var arr = ['Zero','One','Two','A kind of','Four','Five','Six','Seven','Eight','Nine'] var s = "20170401"; s.replace(/\d/g,function(){ return arr[arguments[0]] }) <!--"One hundred and one hundred and one hundred and one hundred and one hundred."-->
<!--1000-bit splitter--> //1 "2343289".replace(/^(\d{1,3})((?:\d{3})+)$/,function(){ return arguments[1]+"," + arguments[2].replace(/(\d){3}(?!$)/g,function(){ <!--(?=$),(?!$)Forward Forecast and Negative Forecast --> return arguments[0]+ "," }) }) //2 var str = '2343289'; str.replace(/(\d)(?!$)/g,function(res,i){ if((str.length-i-1)%3==0) { return res+ "," }else{ return res; } }) //3 var str = '2343289'; str = str.split('').reverse().join(''); str = str.replace(/(\d{3})/g,'$1,'); str.split('').reverse().join(''); <!--Results: 2.,343,289-->
8. Regular? Usage
Represents 0 to 1 (?) after a quantifier.
var reg = /^(\+|-)?\d+(\.\d+)?$/;
Match not capture (?:)
var reg = /^(?:\+|-)?\d+(\.\d+)?$/
Cancel regular greedy capture and put it after the quantifier.
var reg = /\d+/; res = reg.exec('ducen2017niubi12'); //The catch is ["2017"] not 2 //Solve the greed of regularity (add a quantifier character after the quantifier character? ) var reg = /\d+?/; res = reg.exec('ducen2017niubi12'); //The catch is ["2"];
Positive Prediction and Negative Prediction (Conditions)
(?! n) - > Matches any string immediately following the specified string n. (?= n) - > Matches any string that is not immediately followed by the specified string n.