Typeof variable types can be obtained by using typeof in JS
Value types: variable is itself contains gives to its value, its variable itself and save the data is stored in the memory block of the stack Reference types, reference types, of course, is assigned to the object on the heap or data variables, according to the official point of explanation is a reference type variable includes only the data reference
Objects, arrays, and functions extend their properties indefinitely, which may take up a lot of memory
Typeof ABC //”undefined” typeof NaN //”number” typeof NULL //”object” typeof console.log //”function” copy code Typeof can only distinguish value types, Function NaN denotes a special non-numeric value, and null is a null pointer that does not point to any address. Typeof distinguishes between five basic types: String, Boolean, number, undefined, symbol, and function variable calculations can be cast:
String concatenation == operator
100 == ‘100’ //true 0 == “” //true null == undefined //true copy code if statement
var c = '';
if(c){
//....
}
Copy the code
Copy code logic operations
console.log(10 && 0); //0 console.log(” || ‘abc’); //’abc’ console.log(! window.abc); Var a = 100; var a = 100; console.log(!! a);
In js logic operations, 0, NaN, “”, null, false, undefined will be judged as false, Everything else is true var add_level = (5 && add_step = = 1) | | (10 && add_step = = 2) | | (12 && add_step = = 4) | | (15 && add_step = = 5) | | 0; Copying code var add_level = {‘ 5 ‘1,’ 10:2, ’15’, 5, ’12:4} [add_step] | | 0; / / shorter copying code when using = = = when using = = if (obj. A = = null) {/ / here is equivalent to obj. A = = = null | | obj. A = = = undefined, short / / this is the recommended method and in the jquery source Function (a,b){if(a == null){… function (a,b){if(a == null){… If (XXX == null){if(XXX == null){if(XXX == null){if(XXX == null){if(XXX == null)
JSON is a built-in JS object that uses two apis
JSON. Stringify ({} a: 10, b: 20) JSON. Parse (‘ {” a “: 10,” b “: 20} ‘) duplicate code At the same time is also a kind of data format
Prototype and Prototype Chain Prototype rules
All reference types (arrays, functions, objects) have object properties and can be extended as they wish. All reference types (arrays, objects, functions) have a __proto__ attribute, whose value is a normal object. All functions have a Prototype attribute, The proto__ property refers to the prototype property of its constructor. When trying to get a property of an object, if the object doesn’t have the property itself, So go back to his __proto(that is, its constructor’s prototype)
Prototype chain
instanceof
Instanceof: Method used to determine which constructor a reference type belongs to
F instanceof Foo
F instance Object = Foo. Prototype = f instance Object
Var arr = [] arr instanceOf Array //true typeof arr //object Object. The prototype. ToString. Call (arr) = = = “[Object Array]” write an example of a prototype chain inheritance function Elem (id) {this. Elem = document.getElementById(id); } Elem.prototype.html = function(val){ var elem = this.elem; if(val){ elem.innerHtml = val; return this; }else{return em.innerhtml; }}
Elem.prototype.on = function(type,fn){ var elem = this.elem elem.addEventListener(type,fn) }
var div1 = new Elem(‘content_wrapper’) //div1.html(‘
ds
‘) //div1.on(‘click’,function(){ // alert(‘clicked’) // } //) div1.html(‘
Zoom in, zoom in, send van der SAR a bigger one on me
javascript
The new object becomes an object linked to the prototype binding this returns the new object
function create() { let obj = new Object() let Con = [].shift.call(arguments) obj.proto = Con.prototype let result = Con.apply(obj, arguments) return typeof result === ‘object’ ? Result: obj} copy code zepto source code how to use prototype chain three, scope and closure
Topic:
This can be used in several different scenarios. Create 10 < a> tags and click on them to pop up the corresponding serial number
Execution context
Scope: a paragraph
console.log(a) //undefined var a = 100 fn(‘zhangsan’) //’zhangsan’ 20 function fn(name){ age = 20 console.log(name,age) var age }
Function declarations are extracted from the copy code, and function expressions will use the same placeholder as variables. The variable definition, function declaration, this, and arguments will be extracted before the function is executed
TypeError:fn1 is not a function var a = function(){TypeError:fn1 is not a function var a = function(){TypeError:fn1 is not a function var a = function(){ // expression} copies the code
Variable promotion: var a; Function promotion: to declare a function earlier
fn(‘zhangsan’)
Function fn(name){// function console.log(this) console.log(arguments)
age = 20
console.log(name,age)
var age
bar(100)
function bar(num){
console.log(num)
}
Copy the code
} Duplicate code to illustrate several different usage scenarios for this
Execute as constructor as object property as window call, apply, bind
var a = { name : ‘A’, fn:function(){ console.log(this.name) } }
a.fn() //this === a a.fn.call({name:’B’}) //this === {name:’B’} var fn1 = a.fn fn1() //this === window Copy the code this to verify the value scope at execution time
There is no block-level scope
If (true){var name = ‘zhangsan’} console.log(name) copies code function scope and global scope
var a = 100 function fn(){ var a = 200 console.log(‘fn’,a) }
console.log(‘global’,a)
fn()
Copy the code scope chain
How to understand scope:
The free variable scope chain is the two scenarios of the lookup closure of the free variable
Var a = 100 function fn(){var b = 200 console.log(a) console.log(b)} var a = 100 function fn(){var b = 200 console.log(b)} All the way to the parent scope, Var a = 100 function F1(){var b = 200 function F2(){var c = 300 console.log(a) {var c = 300 console.log(b) //b is the free variable console.log(c)} F2()} F1() the copy code closure scope is defined, not executed
Closure usage scenarios:
Function as the return value
Function F1(){var a = 100 return function(){console.log(a)}}
Var f1 = f1() var a = 200 f1() copies the code function as an argument
Function F1(){var a = 100 return function(){console.log(a)}
var f1 = F1()
function F2(fn){ var a = 200 fn() }
F2(f1)
In a scope, a statement declaring a variable is resolved by default to declare it at the beginning of the scope. 2. 3. Create 10 < a> tags and click on them to pop up the corresponding serial number
Error writing
var i,a for(i = 0; i<10; i++){ a = document.createElement(‘a’) a.innerHTMl = i + ‘ ‘ a.addEventListener(‘click’,function(e){ e.preentDefault() Alert (I)}) document. The body. The appendChild (a)} copying code spelled correctly
var i,a for(i = 0; i < 10; i++){ (function(i){ var a = document.createElement(‘a’) a.innerHTML = i + ‘ ‘ a.addEventListener(‘click’,function(e){ E.p reventDefault alert () (I)}) document. The body. The appendChild (a) (I)}}) 4, how to understand the scope copying code subject
The free variable scope chain is the two scenarios of the lookup closure of the free variable
In practice, closures are mainly used to encapsulate variables and converge permissions
function isFirstLoad(){ var _list = []; return function(id){ if(_list.indexOf(id) >= 0){ return false; }else{ _list.push(id); return true; } }} var firstLoad = isFirstLoad(); firstLoad(10); Copy code 4. Asynchronous and single threaded
Topic:
What is the difference between synchronous and asynchronous? Take an example of synchronization and asynchrony respectively. What are the scenarios where asynchrony is used in the front end of the setTimeout pen test
Knowledge:
What is asynchronous (versus synchronous) front-end using asynchronous scenarios asynchronous versus single-threaded
What is asynchrony? Does a blocking program run when asynchrony is required
In case of possible waiting
Timing task: setTimeout, setTimeInterval network request: ajax requests, dynamicLoad event binding
Log (100) setTimeout(function(){console.log(200)},1000) Console. log(300) copies the code to execute the first line and prints 100. After executing setTimeout, the function passed in setTimeout is temporarily saved and not executed immediately. When it is idle, it immediately looks to see if there are any temporary setTimeout functions to execute. If it finds that the setTimeout functions do not need to wait for any time, it immediately comes to execute them
What is the difference between synchronous and asynchronous? For example, synchronization blocks code execution, while asynchrony does not. Console.log (1)
setTimeout(function(){ console.log(2) },0)
console.log(3)
setTimeout(function(){ console.log(4) },1000)
Console. log(5) copy code pen (5) test 3: front-end use asynchronous scenarios have what need to wait, because JS is a single-threaded language
The title
Get the date in 2017-06-10 format to get a random number, the requirement is the length of the string format to write a general purpose forEach function that can traverse objects and arrays
Date date.now () // Gets the current number of milliseconds
Var dt = new Date() dt.getTime() dt.getYear () dt.getMonth() dt.getDate() dt.getDate() Dt.gethours () // hour (0-23) dt.getminutes () // minute (0-59) dt.getseconds () // second (0-59) Copy code Math math.random () : Can be used to clear cache Array
ForEach iterates through all the data every determines whether all elements meet the criteria some determines whether at least one element meets the criteria sort Map reassembles the elements to create a new array >- Filters the elements that meet the criteria
array.forEach
arr.forEach( function(item,index){ console.log(index,item); }); Copy the code array.every
Var arr = [1, 2, 3, 4, 5]; Var result = arr.every(function(index,item){if(item<6) return true}); console.log(result); Copy the code array.some
var result = arr.some(function(index,item){ if(item<5) return true; }); console.log(result);
Copy the code arry.sort
Var arr2 = arr.sort(function(a,b){return a-b; //return b-a; }) copy the code array.map
Arr.map (function(item,index){return “+index+’:’+item+’}
Var arr2 = arr.filter(function (item,index){if(item >= 2) return true}) var obj = {x:100, y:200, z:300 }
var key
For (key in obj){if(obj.hasownProperty (key)){console.log(key,obj[key])}} for(key in obj){if(obj.hasownProperty (key)){console.log(key,obj[key])} formatDate(dt){ if(! dt){ dt = new Date() }
Var year = dt.getFullYear() var month = dt.getMonth() + 1 var date = dt.getDate() if(month < 10){// Force conversion month = '0' + Month} if(date < 10){// Cast date = '0' + date} // Cast return year + '-' + month + '-' + dateCopy the code
}
Var dt = new Date() var formatDate = formatDate(dt) console.log(formatDate) The value must be a string of the same length. Var random = math.random () + ‘0000000000’; Var random = random. Slice (0, 10); Function forEach(obj,fn){var key if(obj instanceof Array){// If (obj instanceof Array) ForEach (function(item,index){fn(index,item)})}else{for(key in obj){fn(key,obj[k])}}}
Js-web-api:
Knowledge:
Js basics: ECMA262 standard js-web-api: W3C standard
The W3C standard defines JS as follows:
DOM operations BOM operation events bind to Ajax request (including HTTP protocol) storage
DOM manipulation
The nature of DOM Document, Object, Model Browsers take HTML code, structure a browser can recognize and JS can operate on a Model
DOM node operations
Get DOM node
The Attribute and properity
Attribute: an attribute on an HTML tag, such as ID, class, and value, and a custom attribute. Its value can only be a string. There are three related methods for this attribute: setAttribute, getAttribute, and removeAttribute. Note: When using setAttribute, the function must take two arguments, setAttribute (attributeName,value), which will be compiled as a string regardless of the value type. Adding attributes to an HTML tag is essentially the same as writing attributes inside the tag, so the attribute values will eventually be compiled as strings. Property: is the value of a property on a DOM object that JS gets, such as a, which you can think of as a basic JS object. This node contains properties such as value, className, and methods such as onclik. A JS object has a bunch of properties, and it’s called Properties, and properties has other properties and attributies, and attributies has a bunch of attributes. Commonly used attributes, such as ID, class, and name, are generally attached to JS objects as property, and can be evaluated and assigned as property
DOM structure manipulation
Interview question 1: What kind of basic data structure is DOM? Tree interview question 2: What are the common apis for DOM manipulation?
Obtain the DOM node, property and Attribute of the node, obtain the parent node, obtain the child node, and delete the node
Interview question 3: What is the difference between a DOM node attR and a property? A property is a modification of an Attribute of a JS object. Attribute is a modification of an Attribute of an HTML tag
Question:
How to detect browser types and disassemble parts of urls
knowledge
navigator screen location history
navigator & screen
//navigator var ua = navigator.userAgent var isChrome = ua.indexOf(‘chrome’) console.log(isChrome)
//screen console.log(screen.width) console.log(screen.height)
//location console.log(location.href) console.log(location.protocol) console.log(location.pathname) console.log(location.search) //? Console. log(location.hash) // after the # sign
//history history.back() history.forward(
Topic:
Write a generic event listener function that describes the time bubbling process for a page with an infinite drop-down load of images, how to bind events to each image
Knowledge:
Generic event binding event bubble agent
Var BTN = document.getelementById (‘btn1’) btn.adDeventListener (‘click’, function(event) { console.log(‘clicked’) })
function bindEvent(elem, type, fn) { elem.addEventListener(type, fn) }
var a = document.getElementById(‘link1’) bindEvent(a, ‘click’, function(e) { e.preventDefault(); // Prevents the default action alert(‘clicked’)} from copying code for compatibility with earlier versions of IE
The lower version of IE uses attachEvent binding events, which is different from the W3C standard. The lower version of IE is rarely used, and many websites do not support the compatibility of the lower version of IE
The event bubbling e.toppropatation () // cancels the bubbling agent
a2
a3
a4
var div1 = document.getElementById(‘div1’) div1.addEventListener(‘click’,function(e){ var target = e.target If (target. NodeName === ‘A’){alert(target. InnerHTMl)}}) function bindEvent(elem, type, selector, fn) { if (fn == null) { fn = selector selector = null }
elem.addEventListener(type, function(e) {
var target
if (selector) {
target = e.target
if (target.matches(selector)) {
fn.call(target, e)
}
} else {
fn(e)
}
})
Copy the code
}
Var div1 = document.getelementById (‘div1’) function(e) { console.log(this.innerHTML) })
Var a = document.getelementById (‘a1’) bindEvent(div1, ‘click’) Function (e) {console.log(a.innerhtml)}) copy the code. Interview Question 1: Write a generic event listener function
DOM tree structure event bubble organization bubble bubble application
Interview question 3: For a page with an infinite drop-down load of images, how do I bind events to each image
There are two advantages to using proxies
Seven, Ajax
Topic:
Several implementations of Manually writing an Ajax, independent of third-party libraries, across domains
Knowledge:
XmlHttpRequest Status code description Cross-domain
XMLHttpRequest var xhr = new XMLHttpRequest()
xhr.open(“GET”,”/api”,false)
Xhr.onreadystatechange = function(){ ReadyState == 4){if(xhr.status == 200){alert(xhr.responsetext)}}}
Xhr. send(null) The copy code is incompatible with IE
The low version of IE uses ActiveXObject, which is different from the W3C standard. The low version of IE has been used very little, and many websites have not supported the compatibility of the low version of IE: understand it, no need to dig into it. If you meet the low version of IE demanding interview, give up
.
Status Code Description
0 – (uninitialized) Send () method not called 1 – (loaded) Send () method called, sending request 2 – (loaded) Send () method completed, All corresponding contents have been received. 3 – (interaction) Parsing the response contents. 4 – (Completed) Parsing the response contents is complete and can be invoked on the client
.
The status shows that
2XX – Indicates that the request was successfully processed. For example, if 200 3XX – requires redirection, the browser directly redirects to 4XX – client request error, such as 404 5XX – server error
Cross domain
What is cross-domain
Browsers have the same origin policy and do not allow Ajax to access interfaces of other domains. Cross-domain conditions include protocol, domain name, and port
Three tags that can cross domains
Three tag scenarios
Used for statistics, statistics sites may be other domains (and without any compatibility issues)
Cross attention issues
All cross-domain requests must be approved by the information provider. If they can be obtained without permission, the browser’s same-origin policy is vulnerable
JSONP implementation principle
Loading coding.xxx.com/classindex…. There is not necessarily a classindex. HTML file on the server side. The server can dynamically generate a file on request, and return the general principle
// Return the content format callback({x:100,y:200})
Set HTTP headers on the server side of the replication code
Cookie, sessionStorage, localStorage
Will the capacity be carried into Ajax API ease of use
Ios Safari hidden mode localStorage.getItem error Suggest a unified use try-catch encapsulation copying code buckets of HTML + CSS interview arrangement interview — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — – > click here senior front-end interview arrangement (such as the three framework in-depth knowledge) — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — – > click here javascript performance optimization — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — – > click here javascript design patterns — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — > HTTP related interview here — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — – > click here
Kinshan Link: juejin.cn/post/684490… The copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source. (reprinted from juejin.cn/post/684490…)