经典JavaScript手写面试题和答案

在这里插入图片描述


实现一个函数去重?

function unique(array) {
    
    
  return Array.from(new Set(array));
}

实现一个函数,判断指定元素在数组中是否存在?

function includes(array, value) {
    
    
  for (let i = 0, len = array.length; i < len; i++) {
    
    
    if (array[i] === value) {
    
    
      return true;
    }
  }
  return false;
}

实现一个函数,将给定字符串反转?

function reverseString(str) {
    
    
  // 将字符串分割成一个数组
  const arr = str.split('');
  // 反转数组
  arr.reverse();
  // 将数组拼接成字符串
  return arr.join('');
}

实现一个函数,检测指定字符串是否为回文(即从前往后和从后往前的字符序列都相同)?

function isPalindrome(str) {
    
    
  // 将字符串反转后与原字符串比较
  return reverseString(str) === str;
}
// 利用上题的实现
function reverseString(str) {
    
    
  return str.split('').reverse().join('');
}

实现一个函数,计算两个数的最大公约数?

function gcd(num1, num2) {
    
    
  return num2 ? gcd(num2, num1 % num2) : num1;
}

实现Array.prototype.reduce函数

Array.prototype.myReduce = function(fn, initialValue) {
    
    
  let accum = initialValue === undefined ? undefined : initialValue;
  for (let i = 0; i < this.length; i++) {
    
    
    if (accum !== undefined) {
    
    
      accum = fn.call(undefined, accum, this[i], i, this);
    } else {
    
    
      accum = this[i];
    }
  }
  return accum;
};

实现 一个类似setTimeout的函数delay(ms)

function delay(ms) {
    
    
  return new Promise((resolve) => setTimeout(resolve, ms));
}

实现一个防抖函数debounce(fn, delayTime)

function debounce(fn, delayTime) {
    
    
  let timerId;
  return function() {
    
    
    const context = this;
    const args = arguments;
    clearTimeout(timerId);
    timerId = setTimeout(() => {
    
    
      fn.apply(context, args);
    }, delayTime);
  };
}

实现一个节流函数throttle(fn, intervalTime)

function throttle(fn, intervalTime) {
    
    
  let timerId;
  let canRun = true;
  return function() {
    
    
    const context = this;
    const args = arguments;
    if (!canRun) return;
    canRun = false;
    timerId = setTimeout(function() {
    
    
      fn.apply(context, args);
      canRun = true;
    }, intervalTime);
  };
}

实现一个深度拷贝函数deepClone(obj)

function deepClone(obj) {
    
    
  if (typeof obj !== 'object' || obj === null) {
    
    
    return obj;
  }
  let result = Array.isArray(obj) ? [] : {
    
    };
  for (let key in obj) {
    
    
    if (obj.hasOwnProperty(key)) {
    
    
      result[key] = deepClone(obj[key]);
    }
  }
  return result;
}

猜你喜欢

转载自blog.csdn.net/weixin_48998573/article/details/130840264