一些好用的代码

//正则  
let cash = '1234567890'  
cash.replace(/\B(?=(\d{3})+(?!\d))/g, ',');//"1,234,567,890"  
//非正则的优雅实现  
function formatCash(str) {  
 return str.split('').reverse().reduce((prev, next, index) => {  
 return ((index % 3) ? next : (next + ',')) + prev  
 })  
}  
formatCash(cash);//"1,234,567,890"
let rate = 3;  
"★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate);//"★★★☆☆"
let num = 2.443242342;  
num = num.toFixed(4); //"2.4432"
let array=[1, "1", 2, 1, 1, 3];  
//拓展运算符(...)内部使用for...of循环  
[...new Set(array)];//[1, "1", 2, 3\]  
//利用Array.from将Set结构转换成数组  
Array.from(new Set(array));//[1, "1", 2, 3\]
Math.max方法可以求出给定参数中最大的数。

 Math.max('1','2','3.1','3.2');//3.2  
 Math.min(1,0,-1);//-1

但如果是数组,就不能这样调用了。此时就用到了apply方法。
Function.apply()是JS的一个OOP特性,
一般用来模拟继承和扩展this的用途。
所有函数都有apply(作用域链,参数)这个方法,当作用域链为null时,默认为上文,这个函数的“参数”,接收一个数组。

let arr = ['1','2','3.1','3.2',0,-1];  
//用apply方法  
Math.max.apply(null, arr);//3.2  
Math.min.apply(Math, arr);//-1  
//用拓展运算符  
Math.max(...arr);//3.2  
Math.min(...arr);//-1

隐藏所有指定的元素

const hide2 = (el) => Array.from(el).forEach(e => (e.style.display = 'none'));
// 事例:隐藏页面上所有``元素?
hide(document.querySelectorAll('img'))

检查元素是否具有指定的类

const hasClass = (el, className) => el.classList.contains(className)
// 事例
hasClass(document.querySelector('p.special'), 'special') // true

如何切换一个元素的类?

const toggleClass = (el, className) => el.classList.toggle(className)
// 事例 移除 p 具有类`special`的 special 类
toggleClass(document.querySelector('p.special'), 'special')

获取当前页面的滚动位置

const getScrollPosition = (el = window) => ({
  x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
  y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});
// 事例
getScrollPosition(); // {x: 0, y: 200}

平滑滚动到页面顶部

const scrollToTop = () => {
  const c = document.documentElement.scrollTop || document.body.scrollTop;
  if (c > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, c - c / 8);
  }
}
// 事例
scrollToTop()

如何检查父元素是否包含子元素

const elementContains = (parent, child) => parent !== child && parent.contains(child);

// 事例
elementContains(document.querySelector('head'), document.querySelector('title')); 
// true
elementContains(document.querySelector('body'), document.querySelector('body')); 
// false

你可能感兴趣的:(一些好用的代码)