preface
译 文 : Dead knock 36 JS handwritten topic (after understand, improve really big) only for my personal learning record, perfect in succession
I stopped talking and started writing
1. Data type judgment
/** * Variable type verification *@param {any} arg* /
function myTypeof(arg) {
let type = Object.prototype.toString.call(arg);
return type.slice(8, -1);
}
console.log(myTypeof(1)); //Number
console.log(myTypeof("1")); //String
console.log(myTypeof(true)); //Boolean
console.log(myTypeof(null)); //Null
console.log(myTypeof(undefined)); //Undefined
console.log(myTypeof(Symbol())); //Symbol
console.log(myTypeof(1n)); //BigInt
console.log(myTypeof(new Date())); //Date
console.log(myTypeof([])); //Array
console.log(myTypeof({})); //Object
Copy the code
2. The inheritance
// Create a parent class
function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function () {
console.log(this.name);
};
// Create a subclass
function Children(name, age) {
Parent.call(this, name); // Inherit attributes
this.age = age;
}
Children.prototype = Object.create(Parent.prototype); // Inherit the prototype
Children.prototype.constructor = Children;
Children.prototype.sayAge = function () {
console.log(this.age);
};
// Create an instance
let c = new Children("Zhang".19);
console.log(c);
c.sayName();
c.sayAge();
Copy the code
Compare ES6 class and ES5
3. Array deduplication
- Use ES6 Set to de-weigh
let arr = [1.2.3.1.2.3]
console.log([...new Set(arr)]) / / [1, 2, 3]
// or
console.log(Array.from(new Set(arr))) / / [1, 2, 3]
Copy the code
- Traversal + comparison and de-repetition (Filter, Reduce, for loop, forEach) work in the same way
let arr = [1.2.3.1.2.3]
let map = {}
let result = arr.reduce((prev, cur) = > prev.concat(map[cur] ? [] : (map[cur] = true && cur)), [])
Copy the code
4. Array flattening
- ES6 flat()
let arr = [1[2[3[4]]]];
let result = arr.flat(Infinity); / / [1, 2, 3, 4]
Copy the code
- reduce()
let arr = [1[2[3[4]]]];
function flat(arr) {
return arr.reduce(
(prev, cur) = > prev.concat(Array.isArray(cur) ? flat(cur) : cur),
[]
);
}
let result = flat(arr); / / [1, 2, 3, 4]
Copy the code
- The while loop
let arr = [1[2[3[4]]]];
function flat(arr) {
let result = [...arr]
while (result.some(Array.isArray)) { result = [].concat(... result); }return result
}
let result = flat(arr); / / [1, 2, 3, 4]
Copy the code
5. Deep copy (only copying ordinary object properties)
let obj = [{ a: [1]},1];
function cloneDeep(obj) {
if (typeofobj ! = ='object' || obj === null) return
let result = Object.prototype.toString.call(obj) === "[object Object]" ? {} : [];
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
let value = obj[key];
result[key] = typeof value === "object"? cloneDeep(value) : value; }}return result;
}
Copy the code
6. Event bus
// Follow up
Copy the code
7. Parse URL parameters into objects
// Follow up
Copy the code
8. String template
// Follow up
Copy the code
9. Lazy loading of images
// Follow up
Copy the code
10. Function stabilization
function debound(fun,time){
let timer = null
return function(. arg){
if(timer) clearTimeout(timer)
timer = setTimeout(() = >{
clearTimeout(timer)
fun.apply(this,arg)
},time)
}
}
Copy the code
11. Function throttling
function throttle(fun,time){
let timer = null
return function(. arg){
if(timer) return
timer = setTimeout(() = >{
clearTimeout(timer)
fun.apply(this,arg)
},time)
}
}
Copy the code
12. Coriolization of functions
// Follow up
Copy the code
13. The partial functions
// Follow up
Copy the code
14. JSONP
// Follow up
Copy the code
15. AJAX (a simple wrapper)
function request({
url
method = 'get',
hearders = {},
data
}){
return new Promise((resolve,reject) = >{
let xhr = new XMLHttpRequest()
xhr.open(method,url)
for(let key in hearders){
xhr.setRequestHeader(key,hearder[key])
}
xhr.onreadystatechange = () = > {
if(xhr.readState ! = =4) return
if((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304){
resolve(xhr.responesText)
}else{
reject(new Error(xhr.responesText))
}
}
xhr.send(data)
})
}
Copy the code
16. Array prototype method
// Follow up
Copy the code
16. Function prototype method
- call
Function.prototype.myCall = (obj,... arg){let fun = Symble('fun')
obj[fun] = this
letres = obj[fun](... arg)delete obj[fun]
return res
}
Copy the code
- apply
Function.prototype.myApply = (obj,arg){
let fun = Symble('fun')
obj[fun] = this
letres = obj[fun](... arg)delete obj[fun]
return res
}
Copy the code
- bind
Function.prototype.myBind = (obj,... arg1){let _this = this
let fun = (. arg2) = >{
let that = this instanceof _this ? this: objletres = _this.call(that,... arg1,... arg2)return res
}
fun.prototype = Object.creat(_this.prototype)
return fun
}
Copy the code
17. Implement new keyword
function myNew(fun,... arg){
let obj = Object.create(fun.prototype)
let cnt = fun.apply(obj,arg)
return Object.prototype.toString.call(cnt) === '[object Object]' ? cnt : obj
}
Copy the code
18 Implement the instanceof keyword
function myInstanceof(left,right){
let proto = Object.getPrototypeof(left)
while(true) {if(proto === null) return false
if(proto === right.prototype) return true
proto = Object.getPrototypeof(proto)
}
}
Copy the code
19 promise related
Promise.all() returns a Promise object that iterates through the set of asynchronous tasks. 2. Wrap the asynchronous task as a Promise object with promise.resolve(). 3. Resolve (result) when the number of completed asynchronous tasks is equal to the total number of tasks. 4, Pass. Catch ()
- Parameter is array
function promiseAll(arr){
if(!Array.isArray(arr)){
let errorMsg = "the first parameter of promiseAll must be an Array!"
return Promise.reject(errorMsg)
}
let index = 0
let length = arr.length
let result = []
return new Promise((resolve,reject) = >{
if(length === 0){
resolve(result)
return
}
arr.forEach((item,i) = > {
Promise.resolve(item).then(res= >{
index++
result[i] = res
if(index === length){
resolve(result)
}
}).catch(err= >{
reject(err)
})
})
})
}
Copy the code
- The parameter is an Iterator
function promiseAll(arr){
return new Promise((resolve, reject) = > {
let result = [];
let index = 0;
let totalIndex = 0;
let curIndex = 0;
for (let item of arr) {
totalIndex++;
Promise.resolve(item).then((res) = > {
result[index++] = res;
curIndex++;
if (curIndex === totalIndex) {
resolve(result);
}
})
.catch((e) = > {
reject(e);
});
}
if (totalIndex === 0) { resolve(result); }}); }Copy the code
conclusion
Is this it? What else to eat? I don’t deserve to study