手寫ajax
function ajax(url, successFn){
const xhr= new XMLHttpRequest()
xhr.open('GET', url, true);
xhr.onreadystatechange = function () {
if(xhr.readyState === 4 && xhr.status === 200) {
successFn(xhr.responseText);
}
}
xhr.send();
}
// 結(jié)合Promise
function ajax(url) {
const p = new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.responseText));
} else if (xhr.status === 404) {
reject(new Error("404 NOT FOUND"));
}
}
}
xhr.send(null)
})
return p
}
手寫bind函數(shù)
Function.prototype.bind1 = function () {
// 將參數(shù)解析為數(shù)組
const args = Array.prototype.slice.call(arguments)
// 獲取this(去除數(shù)組第一項(xiàng)救崔,數(shù)組剩余的就是傳遞的參數(shù))
const t = args.shift()
const self = this // 當(dāng)前函數(shù)
// 返回一個(gè)函數(shù)
return function () {
// 執(zhí)行原函數(shù)戈轿,并返回結(jié)果
return self.apply(t, args)
}
}
// 執(zhí)行例子
function fn1(a,b,c) {
console.log('this', this);
console.log(a,b,c)
return 'this is fn1'
}
const fn2 = fn1.bind1({x:100}, 10, 20, 30)
const res = fn2()
console.log(res);
手寫防抖、節(jié)流函數(shù)
防抖:簡(jiǎn)單說就是一開始不會(huì)觸發(fā)决摧,停下來多長(zhǎng)時(shí)間才會(huì)觸發(fā),典型案例就是郵箱輸入檢測(cè)
function debounce(fn, delay) {
let timer; // 維護(hù)一個(gè) timer
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, arguments); // 用apply指向調(diào)用debounce的對(duì)象凑兰,相當(dāng)于this.fn(arguments);
}, delay)
}
}
//測(cè)試用例掌桩,鼠標(biāo)一直動(dòng)不會(huì)觸發(fā)函數(shù),當(dāng)鼠標(biāo)停下來了姑食,觸發(fā)函數(shù)
function testDebounce(e, content) {
console.log(e, content);
}
let testDebounceFn = debounce(testDebounce, 1000); // 防抖函數(shù)
document.onmousemove = function (e) {
testDebounceFn(e, 'debounce'); // 給防抖函數(shù)傳參
}
節(jié)流:不管你鼠標(biāo)無影手不停地去觸發(fā)波岛,他只會(huì)按照自己的delay時(shí)間去觸發(fā),包括第一次觸發(fā)也是多少delay后才會(huì)觸發(fā)音半。
function throttle(fn, delay) {
let timer;
return function () {
if (timer) {
return;
}
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null; // 在delay后執(zhí)行完fn之后清空timer则拷,此時(shí)timer為假,throttle觸發(fā)可以進(jìn)入計(jì)時(shí)器
}, delay)
}
}
//測(cè)試用例曹鸠,鼠標(biāo)移動(dòng)觸發(fā)煌茬,快速移動(dòng)只按照delay的時(shí)間間隔觸發(fā)
function testThrottle(e, content) {
console.log(e, content);
}
let testThrottleFn = throttle(testThrottle, 1000); // 節(jié)流函數(shù)
document.onmousemove = function (e) {
testThrottleFn(e, 'throttle'); // 給節(jié)流函數(shù)傳參
}
手寫Promise
function Promise(executor){
let self = this
self.status = 'pending'
self.value = undefined //接受成功的值
self.reason = undefined //接受失敗回調(diào)傳遞的值
function resolve(value){
if(self.status === 'pending'){
self.value = value //保存成功原因
self.status = 'fulfilled'
}
}
function reject(reason) {
if(self.status === 'pending'){
self.reason = reason //保存失敗結(jié)果
self.status = 'rejected'
}
}
try{
executor(resolve,reject)
}catch(e){
reject(e) // 捕獲時(shí)發(fā)生異常,就直接失敗
}
}
Promise.prototype.then = function (onFufiled, onRejected) {
let self = this;
if(self.status === 'resolved'){
onFufiled(self.value);
}
if(self.status === 'rejected'){
onRejected(self.reason);
}
}
module.exports = Promise;
手寫深拷貝
/**
* 深拷貝
*/
function deepClone(obj) {
//obj為null彻桃,不是對(duì)象數(shù)組坛善,直接返回
if(typeof obj !== 'object' || obj == null){
return obj
}
//初始化返回結(jié)果
let result
//是不是數(shù)組,否則為對(duì)象
(obj instanceof Array) ? result = [] : result = {}
//遍歷obj的key
for(let key in obj){
//保證key不是原型的屬性
if(obj.hasOwnProperty(key)){
//遞歸調(diào)用
result[key] = deepClone(obj[key])
}
}
return result
}
//例子
const obj1 = {
age: 20,
name: "Lee",
address: {
city: '北京'
},
arr: ['a', 'b', 'c']
}
const obj2 = deepClone(obj1)
obj2.address.city = "廣州"
console.log(obj1.address.city)
console.log(obj1)
console.log(obj2) //相互獨(dú)立不影響
手寫jQuery
class jQuery {
constructor(selector){
const result = document.querySelectorAll(selector)
const length = result.length
for(let i=0; i < length; i++){
this[i] = result[i]
}
this.length = length
this.selector = selector
}
get(index){
return this[index]
}
each(fn) {
for(let i=0; i<this.length; i++){
const elem = this[i]
fn(elem)
}
}
on(type, fn){
return this.each(elem => {
elem.addEventListener(type, fn, false)
})
}
}
// 彈窗插件
jQuery.prototype.dialog = function (info) {
alert(info)
}
通用事件監(jiān)聽事件
// 通用事件監(jiān)聽事件
function bindEvent(elem, type, selector, fn) {
// 如果傳了三個(gè)參數(shù)
if(fn == null){
fn = selector
selector = null
}
elem.addEventListener(type, event => {
const target = event.target
if (selector) {
// 代理綁定叛薯,綁定無限個(gè)
if (target.matches(selector)) {
fn.call(target, event)
}
} else {
// 普通綁定
fn.call(target, event)
}
})
}
// 例子
const test1 = document.getElementById("tyre")
const event1 = function () {
console.log(this.innerText);
}
// 綁定多個(gè)
//bindEvent(test1,'click','p',event1)
// 綁定一個(gè)
const event2 = function () {
console.log(this.id);
}
bindEvent(test1,'click',event2)
冒泡排序
// 冒泡排序浑吟,相鄰兩個(gè)一直比較,最后一個(gè)數(shù)最大就不用比較了
function Bubbling(a){
for(var i=0; i<a.length-1; i++){
for(var j=0; j<a.length-1; j++){
if(a[j] > a[j+1]){
var t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}
}
return a
}
選擇排序
// 選擇排序耗溜,先找全部數(shù)中最小的组力,排第一,再找剩下最小的與之交換
function Choice(a){
var min, t;
for(var i=0; i<a.length-1; i++){
min = i;
for(var j = i+1; j<a.length; j++){
if(a[j] < a[min]){
min = j;
}
}
t = a[i];
a[i] = a[min];
a[min] = t
}
return a
}