注意: 不考虑浏览器向下兼容性,不考虑运行效率,不考虑异常,请勿随意用于生产环境。
let getUrlParams = () => Object.fromEntries(new URLSearchParams(location.search).entries())
let dedup = (arr) => Array.from(new Set(arr))
let arr = [1, 1, 2, 2, 3, 3]
let output = dedup(arr) // output: [1, 2, 3]
let repeat = (arr, n) => arr.flatMap(item => new Array(n).fill(item))
let arr = [1, 2, 3]
let output = repeat(arr, 2) // output: [1, 1, 2, 2, 3, 3]
let repeat = (arr, n) => new Array(n).fill(arr).flatMap(item => item)
let arr = [1, 2, 3]
let output = repeat(arr, 2) // output: [1, 2, 3, 1, 2, 3]
let deepClone = (v) => JSON.parse(JSON.stringify(v))
let obj = { a: 0 }
let obj_copy = deepClone(obj)
obj.a = 1
console.log(obj) // { a: 1 }
console.log(obj_copy) // { a: 0 }
let getType = (v) => Object.prototype.toString.call(v).slice(8, -1)
getType(null) // Null
getType(undefined) // Undefined
getType(true) // Boolean
getType(0) // Number
getType(0n) // BigInt
getType('') // String
getType(Symbol()) // Symbol
getType({}) // Object
getType([]) // Array
getType(() => []) // Function
getType(new Set()) // Set
getType(new Map()) // Map
getType(new FormData()) // FormData
let random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
random(0, 100)
let reverse = str => str.split('').reverse().join('');
reverse('javascript') // tpircsavaj
let sum = arr => arr.reduce((a, b) => a + b)
let arr = [1, 2, 3]
sum(arr) // 6
let avg = arr => arr.reduce((a, b) => a + b) / arr.length
let arr = [1, 2, 3]
avg(arr) // 2
let fact = n => n > 0 ? n * fact(n - 1) : 1
fact(5) // 120
let func = (start, end) => start < end ? [start, ...func(start + 1, end)] : [end]
func(1, 5) // [1, 2, 3, 4, 5]
let merge = (...args) => args.flatMap(arg => arg)
merge([1], [2], [3]) // [1, 2, 3]
let clean = (arr) => arr.filter(item => item !== undefined)
let arr = [
{
a: 1
// ...
},
/*
一大堆说明
...
*/
,{
b: 2,
// ...
}
]// [{ a: 1 }, 空, { b: 2 }]
clean(arr) // [{ a: 1 }, { b: 2 }]
let func = n => new Array(n).fill().map((item, idx) => idx + 1)
func(5) // [1, 2, 3, 4, 5]
let fact = n => new Array(n).fill().map((item, idx) => idx + 1).reduce((a, b) => a * b)
fact(5) // 120
let getAToZ = () => new Array(26).fill().map((_, i) => String.fromCharCode(65 + i))
getAToZ().join('') // ABCDEFGHIJKLMNOPQRSTUVWXYZ
let getAToZ = () => new Array(26).fill().map((_, i) => String.fromCharCode(97 + i))
getAToZ().join('') // abcdefghijklmnopqrstuvwxyz
let getZeroToNine = new Array(10).fill().map((_, i) => String.fromCharCode(48 + i))
getZeroToNine().join('') // 0123456789