• Home
  • Archives
  Evan的博客
  • Home
  • Archives
  • 面试
  • 原理笔记
  • 项目实践
  • 其他

JS 常问手写题汇总

2020/10/10 posted in  面试

总结了一些常见的 JS 手写面试题,分享给大家,也供自己复习的时候看。

  • 这里还有一篇面经
  • leetcode 刷题之旅

1. 找出数组中出现次数最高的元素

/**
 * 找到数组中出现频率最高的元素和其频率
 * @param {Array} arr 数组
 * @return {Object}
 */
const findMostFrequency = arr => {
  let mostFrequency = 0
  let mostFrequencyArr = []

  // 这一步能获取到一个Map对象,key是元素,val是其出现的频率
  const map = arr.reduce((pre, cur) => {
    let frequency = pre.has(cur) ? pre.get(cur) : 0
    frequency ? pre.set(cur, ++frequency) : pre.set(cur, 1)
    // 确定最高频率
    mostFrequency = Math.max(mostFrequency, frequency)
    return pre
  }, new Map())

  // 遍历Map,把出现最高频的元素push到mostFrequencyArr
  for (const item of map) {
    if (item[1] == mostFrequency) mostFrequencyArr.push(item[0])
  }

  // 返回结果
  return {
    mostFrequency,
    mostFrequencyArr
  }
}

2. 展平多维数组

let arr = [
  [0, 1],
  [2, 3],
  [4, [5, 6, 7]]
]
const tileArr = arr => {
  return arr.reduce((pre, cur) => pre.concat(Array.isArray(cur) ? tileArr(cur) : cur), [])
}
console.log(tileArr(arr)) // [0, 1, 2, 3, 4, 5, 6, 7]

3. 随机洗牌算法

Array.prototype.shuffle = function() {
  for (let i = this.length - 1; i >= 0; i--) {
    let randomIndex = Math.floor(Math.random() * (i + 1))
    ;[this[randomIndex], this[i]] = [this[i], this[randomIndex]]
  }
  return this
}

4. 全文单词首字母大写

const upperCase = strs => {
  return strs.replace(/\b[a-zA-Z]/g, str => str.toUpperCase())
}

5. 斐波那契数列

const fibonacci = n => {
  if (n === 1 || n === 2) return n === 1 ? 0 : 1
  return fibonacci(n - 1) + fibonacci(n - 2)
}

冒泡排序

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


let arr = [1, 7, 3, 8, 2, 11, 100, -29, 0, -17]
console.log(bubbleSort(arr))

快排

Array.prototype.quickSort = function() {
  if (!this.length) return []
  let leftArr = []
  let rightArr = []
  for (let i = 1; i < this.length; i++) {
    if (this[i] >= this[0]) rightArr.push(this[i])
    if (this[i] < this[0]) leftArr.push(this[i])
  }
  return [...leftArr.quickSort(), this[0], ...rightArr.quickSort()]
}

let arr = [1, 7, 3, 8, 2, 11, 100, -29, 0, -17]
console.log(quickSort(arr))

« Web Component

JS 中的类与继承 »

Evan的博客

Evan 的博客 - 非典型码农,bug永动机
Instagram Weibo GitHub Email RSS

Categories

面试 原理笔记 项目实践 其他 JS Vue 性能优化 算法 计算机网络

Recent Posts

  • 从 HTTP 发展历程重学计算机网络
  • 应届前端的逆袭(中)
  • 应届前端的逆袭(上)
  • 应届前端的逆袭(下)
  • 前端面经复盘

Copyright © 2015 Powered by MWeb,  Theme used GitHub CSS.