整理一些常用的代码片段
一、数组重排序
1 2 3
| const shuffle = (arr) => arr.sort(() => Math.random() - 0.5) const arr = [1, 2, 3, 4, 5] console.log(shuffle(arr))
|
二、复制到剪切板
1 2 3 4 5 6
| const copyToClipboard = (text) => navigator.clipboard && navigator.clipboard.writeText && navigator.clipboard.writeText(text)
copyToClipboard('Hello World!')
|
三、滚动到顶部
behavior:”smooth”:开启平滑滚动
1 2
| const scrollToTop = (element) => element.scrollIntoView({ behavior: 'smooth', block: 'start' })
|
四、检测设备
1 2 3 4 5 6 7 8
| const detectDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( navigator.userAgent ) ? 'Mobile' : 'Desktop'
console.log(detectDeviceType())
|
五、深拷贝对象
1
| const deepCopy = (obj) => JSON.parse(JSON.stringify(obj))
|
六、等待函数
1 2 3 4 5 6 7 8
| const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
const asyncFn = async () => { await wait(1000) console.log('等待异步函数执行结束') }
asyncFn()
|
七、生成随机色
1 2 3 4
| const generateRandomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16)}`
console.log(generateRandomHexColor())
|
八、数组结构与树结构的转换
数组结构数据
1 2 3 4 5 6 7 8
| const arrayData = [ { id: 2, title: '中国', parent_id: 0 }, { id: 3, title: '上海', parent_id: 2 }, { id: 4, title: '浦东新区', parent_id: 3 }, { id: 5, title: '新场古镇', parent_id: 4 }, { id: 6, title: '湖南省', parent_id: 2 }, { id: 1, title: '俄罗斯', parent_id: 0 } ]
|
方法一、使用递归:
1、递归需分为两个函数来完成
2、 以为返回的递归函数主要处理查找 id 添加 children
3、 由转化函数将结果返回
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
function getChildren(data, result, pid) { for (const item of data) { if (item.parent_id === pid) { const newItem = { children: [], ...item } result.push(newItem) getChildren(data, newItem.children, item.id) } } }
function arrayToTree(data, pid) { let result = [] getChildren(data, result, pid) return result }
console.log(arrayToTree(arrayData, 0))
|
方法二、reduce
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
function arrayToTree(data) { const result = [] const obj = data.reduce((pre, cur) => { pre[cur.id] = cur return pre }, {}) for (let item of data) { if (item.parent_id === 0) { result.push(item) continue } if (item.parent_id in obj) { const parent = obj[item.parent_id] parent.children = parent.children || [] parent.children.push(item) } } return result }
|
九、树结构转数组结构
数组结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| const treeData = [ { id: 2, title: '中国', parent_id: 0, children: [ { id: 3, title: '上海', parent_id: 2, children: [ { id: 4, title: '浦东新区', parent_id: 3, children: [{ id: 5, title: '新场古镇', parent_id: 4 }] } ] }, { id: 6, title: '湖南省', parent_id: 2 } ] }, { id: 1, title: '俄罗斯', parent_id: 0 } ]
|
递归方法
1 2 3 4 5 6 7 8 9 10 11
|
function treeToArray(data) { return data.reduce((pre, cur) => { const { children = [], ...item } = cur return pre.concat([{ ...item }], treeToArray(children)) }, []) }
|
十、数据类型验证
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| function typeOf(obj) { const toString = Object.prototype.toString const map = { '[object Boolean]': 'boolean', '[object Number]': 'number', '[object String]': 'string', '[object Function]': 'function', '[object Array]': 'array', '[object Date]': 'date', '[object RegExp]': 'regExp', '[object Undefined]': 'undefined', '[object Null]': 'null', '[object Object]': 'object', '[object FormData]': 'formData' } return map[toString.call(obj)] }
|
十一、只能输入金额
1
| :rules="{ required: itrue, validator: validatePrice, trigger: 'blur' }"
|
1 2 3 4 5 6 7 8 9 10 11
| validatePrice(rule, value, callback) { if (!value) { callback(new Error('请输入价格')) } else if (!/(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(value)) { callback(new Error('请输入有效价格')) } else if (value >= 99999999) { callback(new Error('超过最大金额')) } else { callback() } },
|
十二、数字单位:10000 转换为万(含:亿)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
const transNumberToShort = (value, decimal = 2) => { const k = 10000 const sizes = ['', '万', '亿', '万亿'] let i = undefined let str = '' if (value < k) { str = value } else { i = Math.floor(Math.log(value) / Math.log(k)) str = (value / Math.pow(k, i)).toFixed(decimal) + sizes[i] } return str }
|
十三、简单的数据双向绑定
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> </head>
<body> <div id="app"> <input type="text" id="a" /> <span id="b"></span> </div> </body> <script> var obj = { val: null }
Object.defineProperty(obj, 'val', {
get: function () { return val },
set: function (newVal) { val = newVal if (!val) return document.getElementById('a').value = val
document.getElementById('b').innerHTML = val } }) document.addEventListener('keyup', function (e) {
obj.val = e.target.value }) </script> </html>
|
十四、数组大小排序
1 2 3 4 5 6 7 8 9
| var num = [7, 8, 6, 5, 2]
num.sort((a, b) => { return b - a })
num.sort((a, b) => { return a - b })
|
十五、js 从数组里面取出某两个值作为对象的 key 和 value
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| const data = [ { id: 1, content: '1111' }, { id: 2, content: '2222' }, { id: 3, content: '3333' } ] let lessonObj = data.reduce((obj, cur, index) => { obj[`config_${cur['id']}`] = cur['content'] return obj }, {})
|
十六、深拷贝、浅拷贝
区别:浅拷贝地址还是指向原来那个内存地址,深拷贝是重新开辟一个内存地址
浅拷贝只是对指针的拷贝,拷贝后两个指针指向同一个内存空间
1 2 3
| Object.assign() Array.prototype.slice(0) 扩展运算符(...)
|
深拷贝不但对指针进行拷贝,而且对指针指向的内容进行拷贝
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| JSON.parse(JSON.stringify())
function deepClone(source) { const targetObj = source.constructor === Array ? [] : {} for (keys in source) { if (source.hasOwnProperty(keys)) { if (source[keys] && typeof source[keys] === 'object') { targetObj[keys] = deepClone(source[keys]) } else { targetObj[keys] = source[keys] } } } return targetObj }
|
十七、获取数组中的随机元素
使用 Math.random() 函数和数组长度可以轻松获取数组中的随机元素:
1 2 3
| const arr = [1, 2, 3, 4, 5] const randomElement = arr[Math.floor(Math.random() * arr.length)] console.log(randomElement)
|
十八、数组扁平化
使用 reduce() 函数和 concat() 函数可以轻松实现数组扁平化:
1 2 3 4 5 6 7
| const arr = [ [1, 2], [3, 4], [5, 6] ] const flattenedArr = arr.reduce((acc, cur) => acc.concat(cur), []) console.log(flattenedArr)
|
十九、对象数组根据某个属性值进行排序
1
| const sortedArray = array.sort((a, b) => (a.property > b.property ? 1 : -1))
|
二十、数组中删除特定元素
1
| const removedArray = array.filter((item) => item !== elementToRemove)
|
二十一、检测数组中是否存在重复项
1
| const hasDuplicates = (array) => new Set(array).size !== array.length
|
二十二、判断数组是否包含某个值
1
| const hasValue = arr.includes(value)
|
二十三、首字母大写
1
| const capitalized = str.charAt(0).toUpperCase() + str.slice(1)
|
二十四、获取随机数
1
| const randomInt = Math.floor(Math.random() * (max - min + 1)) + min
|
二十五、获取随机字符串
1
| const randomStr = Math.random().toString(36).substring(2, length)
|
二十六、字符串小驼峰命名
1 2 3 4 5 6
| const str = 'hello world' const camelCase = str .replace(/\s(.)/g, ($1) => $1.toUpperCase()) .replace(/\s/g, '') .replace(/^(.)/, ($1) => $1.toLowerCase()) console.log(camelCase)
|
二十七、计算两个日期之间的间隔
1 2
| const diffInDays = (dateA, dateB) => Math.floor((dateB - dateA) / (1000 * 60 * 60 * 24))
|
二十八、查找日期位于一年中的第几天
1 2
| const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24)
|
二十九、复制内容到剪切板
1 2 3
| const copyToClipboard = (text) => navigator.clipboard.writeText(text)
copyToClipboard('Hello World')
|
三十、获取变量的类型
1 2 3 4 5 6 7 8 9 10 11
| const getType = (variable) => Object.prototype.toString.call(variable).slice(8, -1).toLowerCase()
getType('') getType(0) getType() getType(null) getType({}) getType([]) getType(0) getType(() => {})
|
三十一、检测对象是否为空
1 2
| const isEmptyObject = (obj) => Object.keys(obj).length === 0 && obj.constructor === Object
|