还在担心手写面试题?一文搞定常见js面试手写题目

话不多说,直接进入正题。

数组篇

一. 实现Array.isArray

if (!Array.isArray){
  Array.isArray = function(arg){
    return Object.prototype.toString.call(arg) === '[object Array]';
  };
}

二. 将类数组转换为数组

  1. 借用数组的方法进行转换

// 1. slice

Array.prototype.slice.call(arguments)


// 2. concat

[].concat.apply([], arguments)
  1. es6的方式转换

// 1. ...扩展运算符

[...arguments]


// 2. Array.from()

Array.from(arguments)

三. 判断是否为数组

var a = [];

// 1.基于instanceof

a instanceof Array;

// 2.基于constructor

a.constructor === Array;

// 3.基于Object.prototype.isPrototypeOf

Array.prototype.isPrototypeOf(a);

// 4.基于getPrototypeOf

Object.getPrototypeOf(a) === Array.prototype;

// 5.基于Object.prototype.toString

Object.prototype.toString.call(a) === '[object Array]';

// 6. 通过Array.isArray

Array.isArray(a)

四. 数组方法实现

  1. forEach

 Array.prototype.myForEach = function(fn, context = window){
    let len = this.length
    for(let i = 0; i < len; i++){
        typeof fn === 'function' && fn.call(context, this[i], i)
    }
}
  1. filter

Array.prototype.myFilter = function(fn, context = window){
    let len = this.length,
        result = []

    for(let i = 0; i < len; i++){
        if(fn.call(context, this[i], i, this)){
            result.push(this[i])
        }
    }
    return result
}
  1. every

Array.prototype.myEvery = function(fn, context){
    let result = true,
        len = this.length
    for(let i = 0; i < len; i++){
        result = fn.call(context, this[i], i, this)
        if(!result){
            break
        }
    }
    return result
}
  1. some

Array.prototype.mySome = function(fn, context){
    let result = false,
        len = this.length
    for(let i = 0; i < len; i++){
        result = fn.call(context, this[i], i, this)
        if(result){
            break
        }
    }
    return result
}
  1. findIndex

Array.prototype.myFindIndex = function (callback) {
    for (let i = 0; i < this.length; i++) {
        if (callback(this[i], i)) {
            return i
        }
    }
}
  1. Reduce
Array.prototype.myReduce = function (fn, initialValue) {
    let arr = Array.prototype.call(this)
    let res, startIndex
    res = initialValue ? initialValue : arr[0]
    startIndex = initialValue ? 0 : 1
    for (let i = startIndex; i < arr.length; i++) {
        res = fn.call(null, res, arr[i], i, this)
    }
    return res
}

三. 实现数组扁平化

let ary = [1, [2, [3, 4, 5]]]
  1. 普通递归+concat

const flatten = function(ary){
    let result = []

    for(let i = 0;i<ary.length;i++){
        if(Array.isArray(ary[i])){
            result = result.concat(flatten(ary[i]))
        } else {
            result.push(ary[i])
        }
    }
    return result
}
  1. reduce+concat

const flatten = function(ary){
    return ary.reduce((prev, next)=>{
        return prev.concat(Array.isArray(next) ? flatten(next) : next)
    }, [])
}
  1. while+concat

const flatten = function(ary){
    while(ary.some(item=>Array.isArray(item))){
        ary = [].concat(...ary)
    }
    return ary
}
  1. toString+split

const flatten = function(ary){
    return ary.toString().split(',')
}
  1. flat

const flatten = function(ary){
    return ary.flat(Infinity)
}
  1. 正则

const flatten6 = function(ary){
    let str = JSON.stringify(ary)
    str = str.replace(/([|])/g, '')
    return JSON.parse(`[${str}]`)
}

四. 去重

  1. 利用 ES6 语法(扩展运算符)
const unique1 = (array) => {
  // return Array.from(new Set(array))
  return [...new Set(array)]
}
  1. 利用 forEach() + 对象容器
const unique2 = (array) => {
  const arr = []
  const obj = {}
  array.forEach(item => {
    if (!obj.hasOwnProperty(item)) {
      obj[item] = true
      arr.push(item)
    }
  })
  return arr
}
  1. 利用 forEachindexOf
const unique3 = (array) => {
  const arr = []
  array.forEach(item => {
    if (arr.indexOf(item) === -1) {
      arr.push(item)
    }
  })
  return arr

}
  1. 利用 filter + indexOf
const unique4 = (array) => {
  return array.filter((item,index) => {
    return array.indexOf(item) === index;
  })
}
  1. 利用 forEachincludes (本质同3)
const unique6 = (array) => {
  let result = [];
  array.forEach(item => {
    if(!result.includes(item)){
      result.push(item);
    }
  })
  return result;
 }
  1. 利用 sort
const unique6 = (array) => {
  let result = array.sort(function (a,b) {
    return a - b;
  });

  for(let i = 0;i < result.length;i ++){
    if(result[i] === result[i+1]){
      result.splice(i + 1,1);
      i --;
    }
  }
  return result;
}
  1. 双层for循环
function unique(array) {
    // res用来存储结果
    var res = [];
    for (var i = 0, arrayLen = array.length; i < arrayLen; i++) {
        for (var j = 0, resLen = res.length; j < resLen; j++ ) {
            if (array[i] === res[j]) {
                break;
            }
        }

        // 如果array[i]是唯一的,那么执行完循环,j等于resLen

        if (j === resLen) {
            res.push(array[i])
        }
    }

    return res;

}

console.log(unique(array)); // [1, "1"]

五. 排序

  1. 冒泡排序

原理:利用数组的前一项与相邻的后一项相比较,判断大/小,交换位置

const bubbleSort = function(ary){
    for(let i = 0; i < ary.length - 1; i++){
        for(let j = 0; j < ary.length - 1 - i; j++){
            if(ary[j] > ary[j+1]){
                [ary[j], ary[j+1]] = [ary[j+1], ary[j]]
            }
        }
    }

    return ary

}
  1. 选择排序

原理:利用数组的某项与后面所有的值相比较,判断大/小,交换位置

const bubbleSort = function(ary){
    for(let i = 0; i < ary.length - 1; i++){
        for(let j = i + 1; j < ary.length; j++){
            if(ary[i] > ary[j]){
                [ary[i], ary[j]] = [ary[j], ary[i]]
            }
        }
    }
    return ary
}
  1. 原生排序

Array.sort((a, b)=>a-b)
  1. 快速排序

原理:取数组的中间值作为基准,判断左右两边的值大或小,添加到相应数组,递归调用,然后将所有的值拼接在一起。

const quick_sort = function(ary){
    if(ary.length < 1){
        return ary
    }


    let centerIndex = Math.floor(ary.length/2)
    let centerVal = ary.splice(centerIndex, 1)[0]


    let left = []
    let right = []
    ary.forEach(item => {
        item > centerVal ? right.push(item) : left.push(item)
    })

    return [...quick_sort(left), ...[centerVal], ...quick_sort(right)]
}
  1. 插入排序

原理:先将数组中的一项添加到新数组中,循环数组每一项与新数组中比较,比较大的值放在后面小的放到新数组的前面。

 const insertion_sort = function(ary){
    let newAry = ary.splice(0, 1)
    for(let i = 0; i < ary.length; i++){
        let cur = ary[i]
        for(let j = newAry.length - 1; j >= 0;){
            if(cur < newAry[j]){
                j--
                j === -1 && newAry.unshift(cur)
            } else {
                newAry.splice(j + 1, 0, cur)
                j = -1
            }
        }
    }
    return [...newAry]
}

六. 最大值与最小值

  1. 假设法

const maxMin = function(ary){
    let [min, max] = [ary[0], ary[1]]
    ary.forEach(ele => {
        min > ele ? min = ele : null
        max < ele ? max = ele : null
    })
    return [min, max]
}
  1. math.max() + 假设法

var arr = [6, 4, 1, 8, 2, 11, 23];
var result = arr[0];
for (var i = 1; i < arr.length; i++) {
    result =  Math.max(result, arr[i]);
}

console.log(result);
  1. reduce

var arr = [6, 4, 1, 8, 2, 11, 23];
function max(prev, next) {
    return Math.max(prev, next);
}

console.log(arr.reduce(max));
  1. 排序

var arr = [6, 4, 1, 8, 2, 11, 23];
arr.sort(function(a,b){return a - b;});
console.log(arr[arr.length - 1])
  1. 利用Math.max

Math.max.apply(null, ary)



// 扩展运算符

Math.max(...arr)



// eval

var max = eval("Math.max(" + arr + ")");

七. 平均值

const balance = function(ary){
    ary.sort((a, b) => a - b)
    ary.shift()
    ary.pop()
    let num = 0
    ary.forEach(item => {
        num += item
    })
    return (num/ary.length).toFixed(2)
}

八. 数组乱序

function shuffle(a) {
    var j, x, i;
    for (i = a.length; i; i--) {
        j = Math.floor(Math.random() * i);
        x = a[i - 1];
        a[i - 1] = a[j];
        a[j] = x;
    }
    return a;
}

九. 将数组扁平化并去除其中重复数据,最终得到一个升序且不重复的数

let arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10];


Array.from(new Set(arr.flat(Infinity))).sort((a,b)=>{ return a-b})

函数篇

一. 判断是否为promise

const isPromise = function(fn){
    return typeof fn.then === 'function'

}

二. 实现call函数

Function.prototype.myCall = function(context,...args) {
    context =  (context ?? window) || new Object(context)
    context.fn = this
    const result = context.fn(args)
    delete context.fn
    return result
}

三. 实现apply函数

Function.prototype.myApply = function(context, arr) {
    context =  (context ?? window) || new Object(context)
    // const args = arguments[1]
    context.fn = this
    const result = arr ? context.fn(...arr) : context.fn()
    delete context.fn
    return result
}

call 的使用场景

1、对象的继承。如下面这个例子:

function superClass () {
    this.a = 1;
    this.print = function () {
        console.log(this.a);
    }
}

function subClass () {
    superClass.call(this);
    this.print();
}


subClass();// 1

subClass 通过 call 方法,继承了 superClass 的 print 方法和 a 变量。此外,subClass 还可以扩展自己的其他方法。

2、借用方法。还记得刚才的类数组么?如果它想使用 Array 原型链上的方法,可以这样:

let domNodes = Array.prototype.slice.call(document.getElementsByTagName("*"));

这样,domNodes 就可以应用 Array 下的所有方法了。

apply 的一些妙用

1、Math.max。用它来获取数组中最大的一项。

let max = Math.max.apply(null, array);

同理,要获取数组中最小的一项,可以这样:

let min = Math.min.apply(null, array);

2、实现两个数组合并。在 ES6 的扩展运算符出现之前,我们可以用 Array.prototype.push来实现。

let arr1 = [1, 2, 3];let arr2 = [4, 5, 6];

Array.prototype.push.apply(arr1, arr2);console.log(arr1); // [1, 2, 3, 4, 5, 6]

四. 实现bind函数

bind() 方法会创建一个新函数。当这个新函数被调用时,bind() 的第一个参数将作为它运行时的 this,之后的一序列参数将会在传递的实参前传入作为它的参数。(来自于 MDN )

Function.prototype.myBind = function (context, ...outerArgs) {  // this->func context->obj outerArgs->[10,20]

  let self = this

  // 返回一个函数

  return function F(...innerArgs) { //返回了一个函数,...innerArgs为实际调用时传入的参数

    // 考虑new的方式
    if(self instanceof F) {      
        return new self(...outerArgs, ...innerArgs)    
    }    // 把func执行,并且改变this即可

    return self.apply(context, [...outerArgs, ...innerArgs]) //返回改变了this的函数,参数合并

  }}

五. new关键字

  1. 实现逻辑

要创建 Person 函数的新实例,必须使用 new 操作符。以这种方式调用构造函数实际上会经历以下 几个步骤:

  1. 创建一个新对象(例如p1)

  2. 将新对象的__proto__属性指向函数的prototype(即p1.proto === Person.prototype )

  3. 将函数的this指向新创建的对象

  4. 返回新对象

4.1. 构造函数没有显式返回值,返回this

4.2. 构造函数有显式返回值,且是基本类型,比如number,string,那么还是返回this

4.3. 构造函数有显式返回值,且是对象类型,比如{a:1},那么返回这个对象

  1. 具体实现

function Person(name,age){
    this.name = name;
    this.age = age;    
    this.sayName = function(){
        console.log(this.name)    
    }
}


//方法一

function createNew(){
    const obj = new Object();    
    const fnconstructor = [].shift.call(arguments);    
    obj.__proto__ = fnconstructor.prototype;        
    const resultObj = fnconstructor.apply(obj,arguments);    
    return typeof resultObj === 'object'? resultObj : obj
}


//方法二

const createNew = (Con, ...args) => {    
    const obj = {}    
    Object.setPrototypeOf(obj, Con.prototype)    
    let result = Con.apply(obj, args)    
    return result instanceof Object ? result : obj
}


const per1 = createNew(Person,'xiaokong',18)

console.log(per1) //{ name: 'xiaokong', age: 18, sayName: [Function] }

六. 防抖函数

防抖的原理就是:你尽管触发事件,但是我一定在事件触发 n 秒后才执行,如果你在一个事件触发的 n 秒内又触发了这个事件,那我就以新的事件的时间为准,n 秒后才执行,总之,就是要等你触发完事件 n 秒内不再触发事件,我才执行。

function debounce(fn,wait){
    var timer = null;
    return function(){
        if(timer !== null){
            clearTimeout(timer);
        }
        timer = setTimeout(fn,wait);
    }
}

七. 节流函数

降低触发的频率,如果持续触发事件,每隔一段时间,只执行一次事件。

function throttle(fn, interval) {
  // 记录上一次的开始时间
  let lastTime = 0
 
  // 真正执行的函数
  const throttle = function () {
 
    // 获取当前事件触发时的时间
    const nowTime = new Date().getTime()
 
    // 使用当前触发的时间和之前的时间间隔以及上一次开始的时间, 计算出还剩余多长时间需要去触发函数
    const remainTime = interval - (nowTime - lastTime)
    if (remainTime <= 0) {
      fn()
      lastTime = nowTime
    }
  }
 
  return throttle
}

八. each函数(jq)

jQuery 的 each 方法,作为一个通用遍历方法,可用于遍历对象和数组。

语法为:

jQuery.each(object, [callback])

回调函数拥有两个参数:第一个为对象的成员或数组的索引,第二个为对应变量或内容。

// 遍历数组

$.each( [0,1,2], function(i, n){
    console.log( "Item #" + i + ": " + n );
});

// Item #0: 0

// Item #1: 1

// Item #2: 2

// 遍历对象

$.each({ name: "John", lang: "JS" }, function(i, n) {
    console.log("Name: " + i + ", Value: " + n);
});

// Name: name, Value: John

// Name: lang, Value: JS
function each(obj, callback) {
    let len, i = 0
    if (Array.isArray(obj)) {
        len = obj.length
        for (; i < len; i++) {
            if (callback.call(obj[i], i, obj[i]) === false) {
                break
            }
        }
    } else {
        for (i in obj) {
            if(callback.call(obj[i], i, obj[i]) === false) {
                break
            }
        }
    }
    return obj
}

对象篇

一. object.create

Object.create = function( o ) {
    function f(){}
    f.prototype = o;
    return new f;
}

二. 浅拷贝

var shallowCopy = function(obj) {
    // 只拷贝对象
    if (typeof obj !== 'object') return;
    
    // 根据obj的类型判断是新建一个数组还是对象
    var newObj = obj instanceof Array ? [] : {};

    // 遍历obj,并且判断是obj的属性才拷贝
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            newObj[key] = obj[key];
        }
    }
    return newObj;
}

三. 深拷贝

var deepCopy = function(obj) {
    if (typeof obj !== 'object') return;
    var newObj = obj instanceof Array ? [] : {};
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            newObj[key] = typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key];
        }
    }
    return newObj;
}

原文链接:https://juejin.cn/post/7345028763564113946 作者:小黄瓜没有刺

(0)
上一篇 2024年3月12日 上午10:22
下一篇 2024年3月12日 上午10:32

相关推荐

发表回复

登录后才能评论