Classic JavaScript Handwritten Interview Questions and Answers

insert image description here


Implement a function to deduplicate?

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

Implement a function to determine whether the specified element exists in the array?

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

Implement a function to reverse a given string?

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

Implement a function to detect whether the specified string is a palindrome (that is, the sequence of characters from front to back and from back to front are the same)?

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

Implement a function to calculate the greatest common divisor of two numbers?

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

Implement the Array.prototype.reduce function

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;
};

Implement a function delay(ms) similar to setTimeout

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

Implement an anti-shake function 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);
  };
}

Implement a throttling function 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);
  };
}

Implement a deep copy function 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;
}

Guess you like

Origin blog.csdn.net/weixin_48998573/article/details/130840264