JS算法题总结

1. 对象深克隆

function deepClone(o) {
  if (o === undefined || o === null || typeof o === "number" || typeof o === "string" || typeof o === "boolean") {
    return o
  } else if (Array.isArray(o)) {
    const arr = []
    for (let item of o) {
      // 递归
      arr.push(deepClone(item))
    }
    return arr
  } else if (typeof o === "object") {
    const obj = {}
    for (let key in o) {
      if (o.hasOwnProperty(key)) {
        obj[key] = deepClone(o[key])
      }
    }
    return obj
  }
}

var p1 = {
  name: "xiaoming",
  age: 17,
  hobby: ["code", "girl"]
}

var p2 = deepClone(p1)
console.log(p2)

console.log(p1.hobby === p2.hobby) // false

2. 数组去重

  • 方法一:
var arr = [1, 1, 1, 2, 2, 2, 3, 3, 3]
var arr2 = [...new Set(arr)]
console.log(arr2) // [ 1, 2, 3 ]
  • 方法二:
var arr = [1, 1, 1, 2, 2, 2, 3, 3, 3]

function unique(arr) {
  var res = []
  for (let item of arr) {
    if (!res.includes(item)) {
      res.push(item)
    }
  }
  return res
}

console.log(unique(arr)) // [ 1, 2, 3 ]

3. 数组扁平化

  • 方法一:
// es6
   arr = arr.flat(Infinity)
  • 方法二:
// 数组扁平化
function flatten(arr){
  var res = []
  for(let item of arr){
    if(Array.isArray(item)){
      res = res.concat(flatten(item))
    }else {
      res.push(item)
    }
  }
  return res
}

4. 冒泡排序

// 冒泡排序
    function bubbleSort(arr) {
      for (let i = 0; i < arr.length - 1; i++) {
        for (let j = 0; j < arr.length - 1 - i; j++) {
          if (arr[j] > arr[j + 1]) {
            [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]
          }
        }
      }
      return arr
    }

你可能感兴趣的:(JS算法题总结)