手写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();
}
// 结合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函数
Function.prototype.bind1 = function () {
// 将参数解析为数组
const args = Array.prototype.slice.call(arguments)
// 获取this(去除数组第一项,数组剩余的就是传递的参数)
const t = args.shift()
const self = this // 当前函数
// 返回一个函数
return function () {
// 执行原函数,并返回结果
return self.apply(t, args)
}
}
// 执行例子
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);
手写防抖、节流函数
防抖:简单说就是一开始不会触发,停下来多长时间才会触发,典型案例就是邮箱输入检测
function debounce(fn, delay) {
let timer; // 维护一个 timer
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, arguments); // 用apply指向调用debounce的对象,相当于this.fn(arguments);
}, delay)
}
}
//测试用例,鼠标一直动不会触发函数,当鼠标停下来了,触发函数
function testDebounce(e, content) {
console.log(e, content);
}
let testDebounceFn = debounce(testDebounce, 1000); // 防抖函数
document.onmousemove = function (e) {
testDebounceFn(e, 'debounce'); // 给防抖函数传参
}
节流:不管你鼠标无影手不停地去触发,他只会按照自己的delay时间去触发,包括第一次触发也是多少delay后才会触发。
function throttle(fn, delay) {
let timer;
return function () {
if (timer) {
return;
}
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null; // 在delay后执行完fn之后清空timer,此时timer为假,throttle触发可以进入计时器
}, delay)
}
}
//测试用例,鼠标移动触发,快速移动只按照delay的时间间隔触发
function testThrottle(e, content) {
console.log(e, content);
}
let testThrottleFn = throttle(testThrottle, 1000); // 节流函数
document.onmousemove = function (e) {
testThrottleFn(e, 'throttle'); // 给节流函数传参
}
手写Promise
function Promise(executor){
let self = this
self.status = 'pending'
self.value = undefined //接受成功的值
self.reason = undefined //接受失败回调传递的值
function resolve(value){
if(self.status === 'pending'){
self.value = value //保存成功原因
self.status = 'fulfilled'
}
}
function reject(reason) {
if(self.status === 'pending'){
self.reason = reason //保存失败结果
self.status = 'rejected'
}
}
try{
executor(resolve,reject)
}catch(e){
reject(e) // 捕获时发生异常,就直接失败
}
}
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,不是对象数组,直接返回
if(typeof obj !== 'object' || obj == null){
return obj
}
//初始化返回结果
let result
//是不是数组,否则为对象
(obj instanceof Array) ? result = [] : result = {}
//遍历obj的key
for(let key in obj){
//保证key不是原型的属性
if(obj.hasOwnProperty(key)){
//递归调用
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) //相互独立不影响
手写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)
}
通用事件监听事件
// 通用事件监听事件
function bindEvent(elem, type, selector, fn) {
// 如果传了三个参数
if(fn == null){
fn = selector
selector = null
}
elem.addEventListener(type, event => {
const target = event.target
if (selector) {
// 代理绑定,绑定无限个
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);
}
// 绑定多个
//bindEvent(test1,'click','p',event1)
// 绑定一个
const event2 = function () {
console.log(this.id);
}
bindEvent(test1,'click',event2)
冒泡排序
// 冒泡排序,相邻两个一直比较,最后一个数最大就不用比较了
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
}
选择排序
// 选择排序,先找全部数中最小的,排第一,再找剩下最小的与之交换
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
}