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)
频率最高的字母或数字
(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
for (let i = n - 1; i > 0; i--) {
count = count * i
}
let arrNum = Array.from(String(count))
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('')
return left === right
}
isPalindrome()
字符串匹配
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运算符
function Fun(age, name) {
this.age = age
this.name = name
}
function create(fn, ...args) {
let obj = {}
Object.setPrototypeOf(obj, fn.prototype)
let result = fn.apply(obj, args)
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
}
const newTarget = deepClone(target)
</script>
</body>
</html>
防抖
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)
}
}
}