js合集

数组合并

const arr1 = ['a', 'b']; const arr2 = ['c']; const arr3 = ['d', 'e']
let result1 = arr1.concat(arr2,arr3)
let result2 = [...arr1, ...arr2, ...arr3]
console.log(result1, result2)

数组去重

let a = ['1', '2', '3', 1,NaN,NaN,undefined,undefined,null,null, 'a', 'b', 'b']
let result = new Set(a)
console.log(result)

频率最高的字母或数字

//let str = 'aslxjkgakfakerkxlkfeikakdck'
(function getMax(str = 'aslxjkgakfakerkxlkfeikakdck') {
  let obj = {}
  Array.from(str).forEach((item) => {
    if (obj[item]) {
      obj[item]++
    } else {
      obj[item] = 1
    }
  })

  let max = 0, letter = ''
  for (let item in obj) {
    if (obj[item] > max) {
      max = obj[item]
      letter = item
    }
  }
  console.log(max, letter)
})()

提取数字

let str = '2022-04-23T13:24:06 Europe/Paris'
let res = str.match(/\d+/g)
console.log(res)

数组中最大的差值

let arr = [6, 8, 16, 7, 55, 26, 6, 4, 88, -3]
let res = Math.max(...arr) - Math.min(...arr)
console.log(res)

Promise并发

async function f() {
  const promiseA = fetch( "http:// .. ./ post/1")
  const promiseB = fetch( "http://.../post/2")
  const [a, b] = await Promise.all([promiseA,promiseB]);
}

插入排序

function insertSort(arr, target) {
  if (arr.length === 0) {
    arr.push(target)
    return
  }
  for (let i = arr.length-1; i >= 0; i--) {
    if (target > arr[i]){
      arr.splice(i+1, 0, target)
      break
    }
    if(i === 0) arr.unshift(target)
  }
}

function sort(arr) {
  let result = []
  for (let i = 0; i < arr.length; i++) {
    insertSort(result, arr[i])
  }
  return result
  coe
}

let arr = []
for (let i = 0; i < 15; i++){
  arr.push(Math.floor(Math.random() * 40))
}
console.log(arr)
console.log(sort(arr))

快速排序

function quickSort(arr) {
  if (arr.length <= 1) return arr
  let middle = Math.floor(arr.length / 2)
  let middleValue = arr.splice(middle, 1)[0]
  let leftArr = [], rightArr = []
  for (let i = 0; i < arr.length; i++) {
    arr[i] < middleValue ? leftArr.push(arr[i]) : rightArr.push(arr[i])
  }
  return quickSort(leftArr).concat(middleValue, quickSort(rightArr))
}
let arr = []
for (let i = 0; i<10; i++){
  arr.push(Math.floor(Math.random() * 40))
}
console.log(arr)
console.log(quickSort(arr))

n的阶层有几个0

let n = 7
let count = n
let result = 0
// 求n的阶层
for (let i = n - 1; i > 0; i--) {
  count = count * i
}
//console.log(count)
// n的阶层的十进制有几个0
let arrNum = Array.from(String(count))
//console.log(arrNum)
for (let i = 0; i < arrNum.length; i++) {
  if (arrNum[i] === '0') {
    result++
  }
}
console.log(result)

回文数

function isPalindrome(x) {
  if(x.length === 0) return false;
  x = x.toString()
  let middle  = Math.floor(x.length / 2)
  let left = x.slice(0, middle)
  let start = x.length % 2 === 0 ? middle : middle +1
  let right = x.slice(start).split('').reverse().join('')
  //console.log("left:"+left,"right:"+right)
  return left === right
}
isPalindrome()
/*
* 给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。

回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

例如,121 是回文,而 123 不是。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
* */

字符串匹配

//给定s1 s2 , s1不断地循环移动,s2是否能任意完全匹配s1的结果中的一个?
//如s1 = ABC 循环移动的结果: ABC CAB BCA ABC
function charInclude(s1, s2) {
  let  a = 0
  let len = s1.length
  while (1) {
    a++
    let end = s1.charAt(len - 1)
    let template = s1.substring(0, len - 1)
    s1 = end + template
    console.log(s1)
    if (s1.includes(s2)) return true
    if (a === len) return false
  }
}

console.log(charInclude('ABCDEFGH', 'EDC'))

最大公共前缀

function longestCommonPrefix(strs) {
  let end = 0
  while(strs.every(item => (end < item.length) && (strs[0][end] === item[end]))){
    end ++
  }
  return strs[0].slice(0, end) || ""
}

console.log(longestCommonPrefix(["a"]))

罗马数字转整数

function romanToInt(s) {
  let obj = {
    'I': 1,
    'V': 5,
    'X': 10,
    'L': 50,
    'C': 100,
    'D': 500,
    'M': 1000,
    'a': 4,
    'b': 9,
    'c': 40,
    'd': 90,
    'e': 400,
    'f': 900
  }
  s = s.replace('IV','a')
      .replace('IX','b')
      .replace('XL','c')
      .replace('XC','d')
      .replace('CD','e')
      .replace('CM','f')
  let result = 0
  for (let i = 0; i < s.length; i++) {
    result += obj[s[i]]
  }
  return result
}

console.log(romanToInt("MCMXCIV"))

连续n个数最大和

function sumMax1(arr, n) {
  let end = n
  let max = 0, sum = 0, point = 0
  for (let i = 0; i < n; i++) {
    max += arr[i]
  }
  for (let j = 1; j < arr.length; j++) {
    end++
    sum = 0
    for (let n = j; n < end; n++) {
      sum += arr[n]
    }
    if (sum > max) {
      max = sum
      point = end - n
    }
  }
  return {max1: max, point1: point}
}

function sumMax2(arr, n) {
  let max = 0, sum = 0, point = 0
  for (let i = 0; i < arr.length; i++) {
    if (i === 0) {
      for (let j = 0; j < n; j++) {
        sum += arr[j]
      }
    }else {
      sum = sum - arr[i - 1] + arr[i + n - 1]
    }
    if (sum > max) {
      max = sum
      point = i
    }
  }
  return {max2: max, point2: point}
}
let arr = []
for(let i = 0; i < 15; i++) {
  arr.push(Math.floor(Math.random() * 40))
}
const {max1, point1} = sumMax1(arr, 2)
const {max2, point2} = sumMax2(arr, 2)
console.log('方法一:', arr, arr.slice(point1, point1 + 2), max1)
console.log('方法二:', arr, arr.slice(point2, point2 + 2), max2)

实现new运算符

// 使用new运算符后发生的事情
// 1.创建一个新对象
// 2.将这个新对象的原型指向构造函数的原型
// 3.改变this指向
// 4.对构造函数做返回值判断(基本数据类型则忽略, 返回引用数据类型)

function Fun(age, name) {
  this.age = age
  this.name = name
}

function create(fn, ...args) {
  // 1.创建一个新对象
  let obj = {}
  // 2.将这个新对象的原型指向构造函数的原型
  Object.setPrototypeOf(obj, fn.prototype)
  //obj.__proto__ = fn.prototype
  // 3.改变this指向
  let result = fn.apply(obj, args)
  // 4.对构造函数做返回值判断(基本数据类型则忽略, 返回引用数据类型)
  return result instanceof Object ? result : obj
}

let obj = create(Fun, 18, 'zs')
let obj1 = new Fun(19, 'ls')
console.log(obj)
console.log(obj1)

对象扁平化

// 对象扁平化
function flatten(obj) {
  const result = {};
  function flat(obj, prefix) {
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        const value = obj[key];
        if (typeof value === 'object') {
          flat(value, prefix + key + '.');
        } else {
          result[prefix + key] = value;
        }
      }
    }
  }
  flat(obj, '');
  return result;
}
// 测试
const obj = {
  a: 1,
  b: {
    c: 2,
    d: {
      e: 3,
    }
  }
}
console.log(flatten(obj));

深拷贝

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<script>
  const target = {
    name: 'jack',
    age: 18,
    friend: {
      name: 'Tom',
    }
  }

  function deepClone(target, map = new Map()) {
    //如果不是数组或对象 直接返回值
    if (typeof target !== 'object' || target === null) {
      return target
    }
    //判断要拷贝的是对象还是数组
    let result = Array.isArray(target) ? [] : {}
    //如果有拷贝过这个对象 直接返回
    if (map.get(target)) {
      return map.get(target);
    }
    //存储对应关系
    map.set(target, result)
    //递归
    for (let key in target) {
      //对象原型上的属性不用拷贝 只考虑自身的属性
      if (target.hasOwnProperty(key))
        result[key] = deepClone(target[key], map)
    }
    return result
  }

  //  function deepClone(target, map = new Map()) {
  //  if (typeof target === 'object') {
  //    let cloneTarget = Array.isArray(target) ? [] : {};
  //    console.log(cloneTarget)
  //    if (map.get(target)) {
  //      return map.get(target);
  //    }
  //    map.set(target, cloneTarget);
  //    console.log(map)
  //    for (const key in target) {
  //      cloneTarget[key] = deepClone(target[key], map);
  //    }
  //    return cloneTarget;
  //  } else {
  //    return target;
  //  }
  //};

  const newTarget = deepClone(target)
  //这个方法依然可以实现
  //const newTarget = JSON.parse(JSON.stringify(target))
  //测试
  //newTarget.friend.name = '小明'
  //newTarget.age = 99
  //console.log(target)
  //console.log(newTarget)

</script>
</body>
</html>

防抖

// 防抖 要防抖的方法 等待时间 是否立即执行一次 相当于vue中watch的immediate
//function debounce(func, wait, immediate) {
//  let timeout
//  return function () {
//    //将 this 指向正确的对象。
//    const context = this
//    //event 对象的指向  否则为undefined
//    const args = arguments
//
//    //以新的事件的时间为准
//    if (timeout) clearTimeout(timeout);
//    if (immediate) {
//      // 若没有定时器 callNow的值为真
//      const callNow = !timeout
//      timeout = setTimeout(function(){
//        timeout = null;
//      }, wait)
//      // 立即执行一次
//      if (callNow) func.apply(context, args)
//    } else {
//      timeout = setTimeout(function(){
//        func.apply(context, args)
//      }, wait);
//    }
//  }
//}

//手写
function debounce(fun, wait) {
  let timer = null
  return function() {
    let that = this
    let args = arguments
    clearTimeout(timer)
    timer = setTimeout(() => {
      fun.apply(that, args)
    },wait)
  }
}

节流

  // 节流 与防抖不同 节流按照一定的频率触发事件
function throttle(fun, delay) {
  let flag = true
  return function () {
    let args = arguments
    let that = this
    if (flag) {
      flag = false
      setTimeout(()=>{
        flag = true
        fun.apply(that, args)
      }, delay)
    }
  }
}
Last Updated:
Contributors: 黄定鑫