JS手写题面试突击

137 阅读1分钟
  1. 手写一个闭包?
function makeFun() {
    let name = 'Chrome';
    function displayName() {
        console.log(name)
    }
    return displayName;
}
  1. 手写一个ajax?
function getData(url) {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', url, false);
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                resolve(xhr.responseText);
            }
            else {
                reject(new Error(xhr.responseText));
            }
        };
        xhr.send();
    });
};
  1. js判断数据类型的方法有哪些?
typeof 'aa'
'aa' instanceof String
Object.prototype.toString.call('aa')
  1. 手写防抖函数(多次触发只执行最后一次)?
function debounce(fn, time = 300) {
    let timer;
    return function(...args) {
        timer && cleartTimeout(timer);
        timer = setTimeout(() => {
            fn.apply(this, args);
            timer = null;
        }, time)
    }
}
  1. 实现数组去重的方式有哪些?
Array.from(new Set(arr))
[...new Set(arr)]
function unique(arr) {
    if (!Array.isArray(arr)) {
        console.error('Type error') ;
    }
    arr = arr.sort();
    let res = [];
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] !== arr[i-1]) {
            res.push(arr[i]);
        }
    }
    return res;
}
function unique(arr) {
    if (!Array.isArray(arr)) {
        console.error('Type error') ;
    }
    let res = [];
    for (let i = 0; i < arr.length; i++) {
        if (res.indexOf(arr[i] === -1)) {
            res.push(arr[i])
        }
    }
    return res;
}
  1. 手写一个bind方法?
Function.prototype.myBind = function(context, args) {
    let fn = this;
    return function(...newArgs) {
        fn.apply(context, [...args, ...newArgs]);
    }
}
Function.prototype.myBind = function (context, ...args) {
    const fn = this;
    args = args ? args : [];
    return function newFn(...newArgs) {
        if (this instanceof newFn) {
            return new fn(..args, ...newArgs);
        }
        return fn.apply(context, [...args, ...newArgs]);
    }
}
  1. 实现字符串反转?
str.split('').reverse().join('')
function reverseString(str) {
    let newString = '';
    let len = str.length;
    for (let i = len -1; i >= 0; i--) {
        newString += str[i];
    }
    return newString;
}
  1. 实现数组扁平化?
const flatten = (arr) => arr.toString().split(',').map((item) => +item);
function flatten(arr) {
    while(arr.some(item => Array.isArray(item))) {
        arr = [].concat(...arr)
    }
    return arr;
}
function flatten(arr) {
    return arr.reduce(function(prev, cur) {
        return prev.concat(Array.isArray(cur) ? flatten(cur) : cur)
    }, [])
}
  1. 实现一个深拷贝?
JSON.parse(JSON.stringify(data))
function deepClone(target) {
    if(target !== null && typeof target !== 'object') {
        let target = Array.isArray(target) ? [] : {};
        for (let i in target) {
            if (target.hasOwnProperty(i)) {
                result[k] = deepClone(target[i]);
            }
        }
        return target;
    }
    else {
        return target;
    }
}
  1. 手写冒泡排序?
function bubbleSort(arr) {
    let len = arr.length;
    for (let i = 0; i < len; i++) {
        for (let j = 0; j < len - 1 - i; j++) {
            if (arr[j] > arr[j + 1]){
                var temp = arr[j + 1];
                arr[j + 1] = arr[j];
                arr[j] = temp;
            }
        }
    }
    return arr;
}
  1. 手写快速排序?
function midSort(arr) {
    if (arr.length <= 1) {
        return arr;
    }
    let mid = Math.floor(arrs.length / 2);
    let midNum = nums.splice(mid, 1)[0];
    let left = [];
    let right = [];
    arr.forEach(item => {
        item < midNum ? left.push(item) : right.push(item)
    })
    return midSort(left).concat(midNum, midSort(right));
}
  1. 手写原型链继承?
function SuperType() {}
function SubType() {}
SubType.prototype = new SuperType();
  1. 手写构造函数继承?
function SuperType(){}
function SubType() {
    SuperType.call(this);
}