查询出现次数最多的字符
let a = "aaabbbbbucun"
let map = new Map();
let result = 0
let res = ""
let i = 0
for (item in a) {
if (map.has(a[item])) {
i++
} else {
i = 1
}
map.set(a[item], i)
}
for ([key, value] of map) {
if(value > result){
result = value;
res = key
}
}
快速排序
function quickSort(arr) {
if (arr.length <= 1) {
return arr;
}
const pivotIndex = Math.floor(arr.length / 2);
const pivot = arr.splice(pivotIndex, 1)[0];
const left = [];
const right = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return quickSort(left).concat([pivot], quickSort(right));
}
冒泡排序
let arr = [3, 6, 2, 5, 3, 8]
let a = 0;
for (let i = 0; i < arr.length -1; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
a = arr[i];
arr[i] = arr[j]
arr[j] = a
}
}
}
console.log(arr)
手写斐波那契数列
function fiber(n) {
if (n <= 1) {
return n
} else {
return fiber(n - 1) + fiber(n - 2)
}
}
手写递归
let a = 5;
function digui(n) {
if (n <= 1) {
return 1
} else {
return n * digui(n - 1)
}
}
console.log(digui(a))
数字每千位用逗号隔开
第一种方式:
num.toLocaleString()
第二种方式:
let p = 1234500000000;
function thousands(num) {
let arr = num.toString().split("");
let resultarr = []
let res = arr.reverse().map((item, index) => {
if ((index) % 3 === 0 && index !== 0) {
resultarr.push(",")
}
resultarr.push(item)
})
console.log(resultarr.reverse().join(""),"arr")
}
console.log(thousands(p))
第三种方式:正则表达式
数组扁平化
第一种方式:
arr.flat()
第二种方式:正则表达式
第三种方式:
let arr = [[1, 2, 3], 45, 5, [0, 3]]
let res = []
function flatten(arr) {
arr.map(item => {
if (Array.isArray(item)) {
flatten(item)
} else {
res.push(item)
}
})
return res
}
console.log(flatten(arr), "ooohhhu")
自定义new
function myNew(Fn){
let obj = {};
obj._proto_ = Fn.prototype;
let res = Fn.apply(obj)
console.log(res,"oooo")
return res instanceof Object ? res : obj;
}
function Person() {
this.name = "小红";
this.hhh = "哈哈哈";
}
var obj1 = myNew(Person);
console.log(obj1);
手写防抖和节流
//防抖
function debounce(fn, delay) {
let timer;
return function (...args) {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(this, args)
timer = null
}, 200)
}
}
// 节流
function lodash(fn, delay) {
let start = 0
return function (...args) {
const current = Date.now()
if (current - start < delay) {
fn.apply(this, args)
start = current
}
}
}