什么是 JavaScript ?

Javascript 是一种脚本语言,用于创建动态更新的内容、控制多媒体、动画图像等等。

返回按钮

使用 history.back() 可以创建一个浏览器“返回”按钮。

  1. <button onclick="history.back()">
  2. 返回
  3. </button>

数字分隔符

为了提高数字的可读性,您可以使用下划线作为分隔符:

  1. const largeNumber = 1_000_000_000;
  2. console.log(largeNumber); // 1000000000

事件监听器只运行一次

如果你想添加一个事件监听器并且只运行一次,你可以使用 once 选项:

  1. element.addEventListener('click', () => console.log('I run only once'), {
  2. once: true
  3. });

console.log 变量包装

您在 console.log() 的时候,将参数用大括号括起来,这样可以同时看到变量名和变量值。
JavaScript - 图1

从数组中获取最小值/最大值

您可以使用 Math.min()Math.max() 结合扩展运算符来查找数组中的最小值或最大值。

  1. const numbers = [6, 8, 1, 3, 9];
  2. console.log(Math.max(...numbers)); // 9
  3. console.log(Math.min(...numbers)); // 1

检查 Caps Lock(大小写) 是否打开

您可以使用 KeyboardEvent.getModifierState() 来检测是否 Caps Lock 打开。

  1. const passwordInput = document.getElementById('password');
  2. passwordInput.addEventListener('keyup', function (event) {
  3. if (event.getModifierState('CapsLock')) {
  4. // CapsLock 已经打开了
  5. }
  6. });

复制到剪贴板

您可以使用 Clipboard API 创建“复制到剪贴板”功能:

  1. function copyToClipboard(text) {
  2. navigator.clipboard.writeText(text);
  3. }

获取鼠标位置

您可以使用 MouseEvent 对象下 clientX 和 clientY 的属性值,获取鼠标的当前位置坐标信息。

  1. document.addEventListener('mousemove', (e) => {
  2. console.log(`Mouse X: ${e.clientX}, Mouse Y: ${e.clientY}`);
  3. });

缩短数组

您可以设置 length 属性来缩短数组。

  1. const numbers = [1, 2, 3, 4, 5]
  2. numbers.length = 3;
  3. console.log(numbers); // [1, 2, 3]

console.table() 打印特定格式的表格

语法:

  1. // [] 里面指的是可选参数
  2. console.table(data [, columns]);

参数:

  • data 表示要显示的数据。必须是数组或对象。
  • columns 表示一个包含列的名称的数组。

实例:

  1. // 一个对象数组,只打印 firstName
  2. function Person(firstName, lastName) {
  3. this.firstName = firstName;
  4. this.lastName = lastName;
  5. }
  6. const john = new Person("John", "Smith");
  7. const jane = new Person("Jane", "Doe");
  8. const emily = new Person("Emily", "Jones");
  9. console.table([john, jane, emily], ["firstName"]);

打印结果如下图:
JavaScript - 图2

将字符串转换为数字

  1. const str = '404';
  2. console.log(+str) // 404;

将数字转换为字符串

  1. const myNumber = 403;
  2. console.log(myNumber + ''); // '403'

截取后缀

  1. let suffix = name.substring(name.lastIndexOf("."));//.txt
  2. let suffix =name.substring(name.lastIndexOf(".")+1);//txt

从数组中过滤所有虚值

  1. const myArray = [1, undefined, NaN, 2, null, '@denicmarko', true, 3, false];
  2. console.log(myArray.filter(Boolean)); // [1, 2, "@denicmarko", true, 3]

过滤字符串

  1. const myTech = 'JavaScript';
  2. const techs = ['HTML', 'CSS', 'JavaScript'];
  3. // 普通写法
  4. if (myTech === 'HTML' || myTech === 'CSS' || myTech === 'JavaScript') {
  5. // do something
  6. }
  7. // includes 写法
  8. if (techs.includes(myTech)) {
  9. // do something
  10. }

reduce 数组求和

  1. [1, 2, 3, 4].reduce((a, b) => a + b); // 10

console.log() 样式

您知不知道可以使用 CSS 语句在 DevTools 中设置 console.log 输出的样式:
JavaScript - 图3

元素的 dataset

使用 dataset 属性访问元素的自定义数据属性 (data-*):

  1. <div id="user" data-name="John Doe" data-age="29" data-something="Some Data">
  2. John Doe
  3. </div>
  4. <script>
  5. const user = document.getElementById('user');
  6. console.log(user.dataset);
  7. // { name: "John Doe", age: "29", something: "Some Data" }
  8. console.log(user.dataset.name); // "John Doe"
  9. console.log(user.dataset.age); // "29"
  10. console.log(user.dataset.something); // "Some Data"
  11. </script>

数组去重

  1. // 一位数组去重
  2. let newArr = Array.from(new Set(Arr))
  3. let newArr = [ ...new Set(Arr) ]
  4. // 多位数组去重
  5. const nMap = new Map()
  6. return Arr.filter((e) => !nMap.has(e) && nMap.set(e, 1))
  7. let resources = [
  8. { name: "张三", age: "18" },
  9. { name: "张三", age: "19" },
  10. { name: "张三", age: "20" },
  11. { name: "李四", age: "19" },
  12. { name: "王五", age: "20" },
  13. { name: "赵六", age: "21" }
  14. ]
  15. let temp = {};
  16. resources = resources.reduce((prev, curv) => {
  17. // 如果临时对象中有这个名字,什么都不做
  18. if (temp[curv.name]) {
  19. }
  20. // 如果临时对象没有就把这个名字加进去,同时把当前的这个对象加入到prev中
  21. else {
  22. temp[curv.name] = true;
  23. prev.push(curv);
  24. }
  25. return prev
  26. }, []);
  27. console.log("结果", resources);

数组查重复值or不重复值

  1. // 数组查找重复值
  2. let newArr = Arr.filter((i) => Arr.indexOf(i) !== Arr.lastIndexOf(i))
  3. // 数组查找不重复值
  4. let newArr = Arr.filter((i) => Arr.indexOf(i) === Arr.lastIndexOf(i))

冻结对象

只是浅层冻结,只会对最近一层的对象进行冻结,并不会对深层对象冻结

  1. let obj = { name: 'You', age: 25 };
  2. Object.freeze(obj);
  3. obj.age = 18; // 25 修改失败
  4. delete obj.age; // false 无法删除

数组内是否包含

  1. const list = [ 'foo', 12, 'You', 19 ]
  2. const type = list.includes(12)
  3. console.log(type)
  4. // true
  5. 已知存在数组
  6. a:[1,2,3,4,5,6,7,8,9]
  7. b:[2,6,8]
  8. 需要过滤a中存在b数组的值,可以使用下面方法
  9. const c = a.filter(v => !b.includes(v));

多条件判断

  1. // data是否为空
  2. if (['', null, undefined].includes(data)) {}
  3. // arr内是否包含空数据
  4. arr.includes('', null, undefined)

空值检查

  1. let first = null
  2. let second = first || '空';
  3. console.log(second)
  4. // 空

判断数据类型

  1. // 数组
  2. const Arr = []
  3. const type1 = Arr.constructor === Array
  4. console.log(type1)
  5. // true
  6. // 对象
  7. const obj = {}
  8. const type3 = typeof obj === "object"
  9. console.log(type3)
  10. // true
  11. // 布尔值
  12. let str = new Boolean()
  13. const type2 = str instanceof Boolean
  14. console.log(type2)
  15. // true

JSON的使用

  1. //将一个JSON字符串转换为JavaScript对象
  2. let arrPa = JSON.parse(arr)
  3. //将JavaScript值转换为JSON字符串
  4. let strFy = JSON.stringify(arr)

字符串替换

  1. // 全局替换
  2. s.replace(/啊/g, "额")
  3. // 替换中文字符,获取字符串长度
  4. s.replace(/[\u0391-\uFFE5]/g, 'aa').length

快速浮点数转整数

使用|(位或运算符)将浮点数截断为整数

  1. console.log(23.9 | 0); // 23
  2. console.log(-23.9 | 0); // -23

获取父级元素

  1. const getParentKey = (key, tree) => {
  2. let parentKey;
  3. for (let i = 0; i < tree.length; i++) {
  4. const node = tree[i];
  5. // 判断是不是顶级父
  6. if (node.key == key) {
  7. return node.key;
  8. }
  9. if (node.children) {
  10. if (node.children.some((item) => item.key === key)) {
  11. parentKey = node.key;
  12. } else if (getParentKey(key, node.children)) { // 必须判断是否有返回值
  13. parentKey = getParentKey(key, node.children);
  14. }
  15. }
  16. }
  17. return parentKey;
  18. };

平铺多维数组

flat 展开数组,参数表示要提取嵌套数组的结构深度

  1. //初始化二维数组
  2. const arr = new Array(5).fill(0).map(()=> new Array(5).fill(0));
  3. arr.flat(Infinity);
  4. const getNodeChild = (val) => {
  5. let arr = []
  6. val.reduce((total, item) => {
  7. total.push(item)
  8. if (item.items && item.items.length) {
  9. total.push(...getNodeChild(item.items))
  10. }
  11. return total
  12. }, arr)
  13. return arr
  14. }

拼接

  1. httpUtil: (data) => {
  2. let ret = '?'
  3. for (const [key, value] of Object.entries(data)) {
  4. ret += key + '=' + value + '&'
  5. }
  6. return ret.slice(0, -1)
  7. }

数据分组

  1. // 方法一
  2. const groupArr = (arr, fn) => {
  3. let list = []
  4. for (const value of arr) {
  5. let key = JSON.stringify(fn(value))
  6. list[key] = list[key] || []
  7. list[key].push(value)
  8. }
  9. return Object.keys(list).map(key => ({ key: JSON.parse(key)[0], data: list[key], total: list[key].length }));
  10. }
  11. const getName = groupArr(list, (i) => [ i.name ])
  12. console.log(getName)
  13. 由父子元素对应ID分组
  14. const groupArr = (arr, parentId, childId, keyName) => {
  15. const temp = {};
  16. const tree = {};
  17. arr.forEach(item => {
  18. temp[item[childId]] = item;
  19. });
  20. const tempKeys = Object.keys(temp);
  21. tempKeys.forEach(key => {
  22. const item = temp[key];
  23. const _itemPId = item[parentId];
  24. const parentItemByPid = temp[_itemPId];
  25. if (parentItemByPid) {
  26. if (!parentItemByPid[keyName]) {
  27. parentItemByPid[keyName] = [];
  28. }
  29. parentItemByPid[keyName].push(item);
  30. } else {
  31. tree[item[childId]] = item;
  32. }
  33. });
  34. return Object.keys(tree).map(key => tree[key]);
  35. }
  36. let list = groupArr(arr, 'pid', 'id', 'children');

防抖节流

  1. // 防抖
  2. function debounce(fun, delay) {
  3. let timer = null
  4. return (...rest) => {
  5. clearTimeout(timer)
  6. timer = setTimeout(() => {
  7. fun.apply(this, rest)}, delay)
  8. }
  9. function test(a, b) {
  10. console.log(a, b)
  11. }
  12. let fun = debounce(test, 1000)
  13. fun(1, 2)
  14. // 节流
  15. // 1.时间戳
  16. function throttle(fun, delay) {
  17. let start = 0
  18. return (...rest) => {
  19. let end = + new Date()
  20. if (end - start >= delay) {
  21. fun.apply(this, rest)
  22. start = end
  23. }
  24. }
  25. }
  26. // 2.计时器
  27. function throttle(fun, delay) {
  28. let isActived = false;
  29. return (...rest) => {
  30. if (!isActived) {
  31. fun.apply(this, rest)
  32. isActived = true
  33. setTimeout(()=> isActived = false, delay)
  34. }
  35. }
  36. }
  37. function test(a, b) {
  38. console.log(a, b)
  39. }
  40. let fun = throttle(test, 2000)
  41. fun(1, 2)

实现浅拷贝

  1. // 浅拷贝的实现;
  2. function shallowCopy(object) {
  3. // 只拷贝对象
  4. if (!object || typeof object !== "object") return;
  5. // 根据 object 的类型判断是新建一个数组还是对象
  6. let newObject = Array.isArray(object) ? [] : {};
  7. // 遍历 object,并且判断是 object 的属性才拷贝
  8. for (let key in object) {
  9. if (object.hasOwnProperty(key)) {
  10. newObject[key] = object[key];
  11. }
  12. }
  13. return newObject;
  14. }

实现深拷贝

  1. function deepClone(obj, hash = new WeakMap()) {
  2. if (hash.has(obj)) {
  3. return obj;
  4. }
  5. let res = null;
  6. const reference = [Date, RegExp, Set, WeakSet, Map, WeakMap, Error];
  7. if (reference.includes(obj?.constructor)) {
  8. res = new obj.constructor(obj);
  9. } else if (Array.isArray(obj)) {
  10. res = [];
  11. obj.forEach((e, i) => {
  12. res[i] = deepClone(e);
  13. });
  14. } else if (typeof obj === "Object" && typeof obj !== null) {
  15. res = {};
  16. for (const key in obj) {
  17. if (Object.hasOwnProperty.call(obj, key)) {
  18. res[key] = deepClone(obj[key]);
  19. }
  20. }
  21. } else {
  22. res = obj;
  23. }
  24. hash.set(obj, res);
  25. return res;
  26. }

倒计时

  1. const countDown = (time) => {
  2. let _this = this
  3. this.timeID = null
  4. this.timeID = setInterval(() => {
  5. let d = +time.day
  6. let h = +time.hours
  7. let m = +time.min
  8. let s = +time.sec
  9. s--
  10. if (s < 0) {
  11. m--
  12. s = 59
  13. }
  14. if (m < 0) {
  15. h--
  16. m = 59
  17. }
  18. if (h < 0) {
  19. d--
  20. h = 23
  21. }
  22. d = d < 10 ? '0' + d : d
  23. h = h < 10 ? '0' + h : h
  24. m = m < 10 ? '0' + m : m
  25. s = s < 10 ? '0' + s : s
  26. time.day = d
  27. time.hours = h
  28. time.min = m
  29. time.sec = s
  30. if (time.day != '00') {
  31. _this.nowTime = `${time.day}天${time.hours}:${time.min}:${time.sec}`
  32. } else {
  33. _this.nowTime = `${time.hours}:${time.min}:${time.sec}`
  34. }
  35. if (d == '00' && h == '00' && m == '00' && s == '00') {
  36. d = h = m = s = 0
  37. this[name] = null
  38. clearInterval(_this.timeID)
  39. _this.timeID = null
  40. }
  41. }, 1000)
  42. }
  43. // 倒计时
  44. const showtime = function () {
  45. const nowtime = new Date() // 获取当前时间
  46. const endtime = new Date('2020/8/8') // 定义结束时间
  47. const lefttime = endtime.getTime() - nowtime.getTime() // 距离结束时间的毫秒数
  48. const leftd = Math.floor(lefttime / (1000 * 60 * 60 * 24)) // 计算天数
  49. const lefth = Math.floor(lefttime / (1000 * 60 * 60) % 24) // 计算小时数
  50. const leftm = Math.floor(lefttime / (1000 * 60) % 60) // 计算分钟数
  51. const lefts = Math.floor(lefttime / 1000 % 60) // 计算秒数
  52. return leftd + '天' + lefth + ':' + leftm + ':' + lefts // 返回倒计时的字符串
  53. }

递归

  1. const familyTree=(arr)=> {
  2. let temp = [];
  3. let forFn = (list)=> {
  4. list.forEach(element => {
  5. if (element.children) {
  6. temp.push(element.id);
  7. forFn(element.children);
  8. }
  9. })
  10. }
  11. forFn(arr);
  12. return temp;
  13. }
  14. }

下载

  1. // 下载
  2. export const DownCsv = (res, name) => {
  3. if (res != null && ['text/plain'].includes(res.type)) {
  4. const blob = new Blob([res], { type: 'text/plain' })
  5. const date =
  6. new Date().getFullYear() + '' +
  7. (new Date().getMonth() + 1) + '' +
  8. new Date().getDate() + '' +
  9. new Date().getHours() + '' +
  10. new Date().getMinutes() + '' +
  11. new Date().getSeconds() + '' +
  12. new Date().getMilliseconds()
  13. const fileName = name + date + '.csv'
  14. if ('download' in document.createElement('a')) {
  15. // 非IE下载
  16. const elink = document.createElement('a')
  17. elink.download = fileName
  18. elink.style.display = 'none'
  19. elink.href = URL.createObjectURL(blob)
  20. document.body.appendChild(elink)
  21. elink.click()
  22. URL.revokeObjectURL(elink.href)
  23. document.body.removeChild(elink)
  24. } else {
  25. // IE10+下载
  26. navigator.msSaveBlob(blob, fileName)
  27. }
  28. }
  29. }

随机字符串

  1. // 数组随机
  2. arr.sort(() => Math.random() - 0.5)
  3. // 获取最后8位
  4. Math.random().toString(36).slice(-8)
  5. // 随机生成32位字符串
  6. const randomString = () => {
  7. let len = 32
  8. let chars =
  9. 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz234567890'
  10. let maxPos = chars.length
  11. let pwd = ''
  12. for (let i = 0; i < len; i++) {
  13. pwd += chars.charAt(Math.floor(Math.random() * maxPos))
  14. }
  15. return pwd
  16. }

数据拷贝

  1. // 浅拷贝
  2. Object.assign({}, obj)
  3. // 深拷贝
  4. JSON.parse(JSON.stringify(obj))
  5. // 深拷贝
  6. export const deepMerge = (obj1, obj2) => {
  7. const isPlain1 = isPlainObject(obj1)
  8. const isPlain2 = isPlainObject(obj2)
  9. if (!isPlain1 || !isPlain2) return shallowMerge(obj1, obj2)
  10. const keys = [
  11. ...Object.keys(obj2),
  12. ...Object.getOwnPropertySymbols(obj2)
  13. ]
  14. keys.forEach(function (key) {
  15. obj1[key] = deepMerge(obj1[key], obj2[key])
  16. })
  17. return obj1
  18. }

深拷贝合并

  1. export const deepMerge = (obj1, obj2) => {
  2. const isPlain1 = isPlainObject(obj1)
  3. const isPlain2 = isPlainObject(obj2)
  4. if (!isPlain1 || !isPlain2) return shallowMerge(obj1, obj2)
  5. const keys = [
  6. ...Object.keys(obj2),
  7. ...Object.getOwnPropertySymbols(obj2)
  8. ]
  9. keys.forEach(function (key) {
  10. obj1[key] = deepMerge(obj1[key], obj2[key])
  11. })
  12. return obj1
  13. }

对象浅合并

  1. export const deepMerge = (obj1, obj2) => {
  2. const isPlain1 = isPlainObject(obj1)
  3. const isPlain2 = isPlainObject(obj2)
  4. if (!isPlain1 || !isPlain2) return shallowMerge(obj1, obj2)
  5. const keys = [
  6. ...Object.keys(obj2),
  7. ...Object.getOwnPropertySymbols(obj2)
  8. ]
  9. keys.forEach(function (key) {
  10. obj1[key] = deepMerge(obj1[key], obj2[key])
  11. })
  12. return obj1
  13. }

检测是否是纯对象

  1. export const shallowMerge = (obj1, obj2) => {
  2. const isPlain1 = isPlainObject(obj1)
  3. const isPlain2 = isPlainObject(obj2)
  4. if (!isPlain1) return obj2
  5. if (!isPlain2) return obj1
  6. const keys = [
  7. ...Object.keys(obj2),
  8. ...Object.getOwnPropertySymbols(obj2)
  9. ]
  10. keys.forEach(function (key) {
  11. obj1[key] = obj2[key]
  12. })
  13. return obj1
  14. }

数组位置互换

  1. list[destination] = list.splice(source, 1, list[destination])[0]

数组移动位置

  1. const Move = (arr, from, to) => {
  2. const list = [].concat(arr)
  3. list.splice(to, 0, list.splice(from, 1)[0])
  4. return list
  5. }

树结构更新

  1. // 更新
  2. export const updateParent = (treeData, key, value, update) => {
  3. const fn = (treeData, key, value, update) => {
  4. if (!treeData.length) return key
  5. for (let index = 0; index < treeData.length; index++) {
  6. if (treeData[index][key] === value) {
  7. const res = treeData[index]
  8. res.children = update
  9. break
  10. }
  11. if (treeData[index].children) {
  12. if (treeData[index].children.length) {
  13. fn(treeData[index].children, key, value, update)
  14. }
  15. }
  16. }
  17. }
  18. fn(treeData, key, value, update)
  19. return treeData
  20. }
  21. const newData = updateParent(data, 'key', item.key, item.children)

生成随机颜色

  1. const generateRandomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16)}`
  2. console.log(generateRandomHexColor())

数组排序

  1. const arr = [2, 1, 4, 3, 5]
  2. arr.sort((a, b) => (b - a)

数组重排序

  1. const shuffle = (arr) => arr.sort(() => Math.random() - 0.5)
  2. const arr = [1, 2, 3, 4, 5]
  3. console.log(shuffle(arr))

复制到剪切板

  1. const copyToClipboard = (text) => navigator.clipboard && navigator.clipboard.writeText && navigator.clipboard.writeText(text)
  2. copyToClipboard("Hello World!")

检测暗色主题

  1. const isDarkMode = () => window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
  2. console.log(isDarkMode())

滚动到顶部

  1. const scrollToTop = (element) =>
  2. element.scrollIntoView({ behavior: "smooth", block: "start" });

滚动到底部

  1. const scrollToBottom = (element) =>
  2. element.scrollIntoView({ behavior: "smooth", block: "end" });

检测元素是否在屏幕中

  1. const callback = (entries) => {
  2. entries.forEach((entry) => {
  3. if (entry.isIntersecting) {
  4. // `entry.target` is the dom element
  5. console.log(`${entry.target.id} is visible`);
  6. }
  7. });
  8. };
  9. const options = {
  10. threshold: 1.0,
  11. };
  12. const observer = new IntersectionObserver(callback, options);
  13. const btn = document.getElementById("btn");
  14. const bottomBtn = document.getElementById("bottom-btn");
  15. observer.observe(btn);
  16. observer.observe(bottomBtn);
  17. http://www.jsxyy.com.cn/voddetail/203079.html

检测设备

  1. const detectDeviceType = () =>
  2. /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
  3. navigator.userAgent
  4. ) ? "Mobile" : "Desktop";
  5. console.log(detectDeviceType());

隐藏元素

  1. const hideElement = (el, removeFromFlow = false) => {
  2. removeFromFlow ? (el.style.display = 'none')
  3. : (el.style.visibility = 'hidden')
  4. }

从 URL 中获取参数

  1. const getParamByUrl = (key) => {
  2. const url = new URL(location.href)
  3. return url.searchParams.get(key)
  4. }

等待函数

  1. const wait = (ms) => new Promise((resolve)=> setTimeout(resolve, ms))
  2. const asyncFn = async () => {
  3. await wait(1000)
  4. console.log('等待异步函数执行结束')
  5. }
  6. asyncFn()

获取字符串中的字符数

  1. const characterCount = (str, char) => str.split(char).length - 1

检查对象是否为空

  1. const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object

等待一段时间再执行

  1. const wait = async (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));

获取两个日期之间的日差

  1. const daysBetween = (date1, date2) => Math.ceil(Math.abs(date1 - date2) / (1000 * 60 * 60 * 24))

重定向到另一个 URL

  1. const redirect = url => location.href = url

检查设备上的触摸支持

  1. const touchSupported = () => ('ontouchstart' in window || DocumentTouch && document instanceof DocumentTouch)

在元素后插入 HTML 字符串

  1. const insertHTMLAfter = (html, el) => el.insertAdjacentHTML('afterend', html)

随机排列数组

  1. const shuffle = arr => arr.sort(() => 0.5 - Math.random())

在网页上获取选定的文本

  1. const getSelectedText = () => window.getSelection().toString()

获取随机布尔值

  1. const getRandomBoolean = () => Math.random() >= 0.5

计算数组的平均值

  1. const average = (arr) => arr.reduce((a, b) => a + b) / arr.length
  1. const observer = new IntersectionObserver(callback: IntersectionObserverCallback, options?: IntersectionObserverInit): IntersectionObserver;
  2. observer.observe(target);
  3. // 最简单的一个使用示例,获取要监听的元素,新建 IntersectionObserver 实例,观察要监听元素,一个根元素可以同时监听多个元素
  4. const divDom = document.getElementsByClassName('hidden');
  5. const observer = new IntersectionObserver(
  6. (entries) => {
  7. entries.forEach((entry) => {
  8. // 过滤掉未出现在视窗中的元素
  9. if (entry.intersectionRatio <= 0) {
  10. return;
  11. }
  12. console.log(entry);
  13. },
  14. { threshold: [0.2, 0.25, 0.5, 1] },);
  15. }
  16. );
  17. observer.observe(divDom[0]);
  18. observer.observe(divDom[1]);
  19. const io = new IntersectionObserver((entrys) => {
  20. entrys.forEach((entry) => {
  21. if(!entry.isIntersecting) return;
  22. loadMore();
  23. })
  24. }, {
  25. rootMargin:'0px 0px 50px 0px'
  26. })
  27. //监听最底部的loadmore是否出现
  28. const lMore = document.querySelector('.load-more');
  29. io.observe(lMore);
  30. onWheel:nativeEvent

编码和解码

escape() 编码, unescape() 解码 废弃
encodeURI 编码,decodeURI 解码
encodeURIComponent 编码,decodeURIComponent 解码

  1. // str = escape(str) //%u4E2D%u56FD
  2. // str = encodeURI(str) //%E4%B8%AD%E5%9B%BD
  3. str = encodeURIComponent(str) //%E4%B8%AD%E5%9B%BD

str.trim().toLowerCase().replace(str[0], str[0].toUpperCase());

  1. const aplitAR = (str, leng) => {
  2. const arr = []
  3. let index = 0
  4. while (index < str.length) {
  5. arr.push(str.slice(index, index += leng))
  6. }
  7. return arr
  8. }
  9. # 转短连接
  10. const randomWord = (leng = 6, url = 'http://localhost:8085/') => {
  11. let str = url
  12. const arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  13. for (let i = 0; i < leng; i++) {
  14. const pos = Math.round(Math.random() * (arr.length - 1))
  15. str += arr[pos]
  16. }
  17. return str
  18. }

获取年月日

  1. const getTime=(date = new Date())=>{
  2. var y = date.getFullYear();
  3. var m = date.getMonth() + 1;
  4. m = m < 10 ? ('0' + m) : m;
  5. var d = date.getDate();
  6. d = d < 10 ? ('0' + d) : d;
  7. var h = date.getHours();
  8. h=h < 10 ? ('0' + h) : h;
  9. var minute = date.getMinutes();
  10. minute = minute < 10 ? ('0' + minute) : minute;
  11. var second=date.getSeconds();
  12. second=second < 10 ? ('0' + second) : second;
  13. return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;
  14. }

获取时间差

  1. const dayjs = require('dayjs');
  2. let sevenDaysAgo_time = dayjs().subtract(7, 'day') // 计算7天前的时间
  3. let sevenDaysAgo = dayjs(sevenDaysAgo_time.$d).format()
  4. //获取到的时间如下
  5. console.log("sevenDay",sevenDaysAgo) //2022-07-18T09:39:33+08:00

价格千位分割

  1. function regexHandleNum(num) {
  2. return String(num).replace(/\B(?=(\d{3})+(?!\d))/g, ','); // 3是千分位,4是万分位
  3. }

动态改变setInterval时间间隔

  1. let Timer = null
  2. let num = 0
  3. let speed = 200
  4. const over = 30
  5. let timeUp = function () {
  6. clearInterval(Timer)
  7. num++
  8. if (10 < num && num < 20) {
  9. speed = 100
  10. } else {
  11. speed = 200
  12. }
  13. if (num >= over) {
  14. clearInterval(Timer)
  15. Timer = null
  16. } else {
  17. Timer = setInterval(timeUp, speed)
  18. }
  19. console.log(num, speed)
  20. }
  21. Timer = setTimeout(timeUp, speed)