Js【功能性】方法(持续维护)

12. 格式化电话号码

//正则                        
let mobile = '18379836654' ;
let mobileReg = /(?=(\d{4})+$)/g;
console.log(mobile.replace(mobileReg, '-')) // 183-7983-6654

11. 获取当前页面所有的图片地址

//正则
const matchImgs = (sHtml) => {
  const imgUrlRegex = /<img[^>]+src="((?:https?:)?\/\/[^"]+)"[^>]*?>/gi
  let matchImgUrls = []
  sHtml.replace(imgUrlRegex, (match, $1) => {
    $1 && matchImgUrls.push($1)
  })
  return matchImgUrls
}
console.log(matchImgs(document.body.innerHTML)) ;//['https://cdn2.jianshu.io/assets/web/nav-logo-4c7bbafe27adc892f3046e6978459bac.png']

10. 千位格式

//正则
const formatMoney = (money) => {return money.replace(new RegExp(`(?!^)(?=(\\d{3})+${money.includes('.') ? '\\.' : '$'})`, 'g'), ',')}
formatMoney('2222222'); // ='2,222,222'

9. 深拷贝函数

const coyeObj = (obj = {})=>{
  let newObj = null;
  //判断是否需要继续进行递归
  if(typeof (obj) == 'object' && obj!==null){
    newobj = obj instanceof Array ? [] : {};
    for(var i in obj){
      newobj[i] = copyObj(obj[i])
    }
  }else{
    newObj = obj;
  }
  return newObj
}

8. 降序比较器函数

const descending = (fn) => (a, b) => {
  const valA = fn(b);
  const valB = fn(a);
  return valA < valB ? -1 : valA > valB ? 1 : 0;
}
const byPrice = descending(val => val.price);
[{ price: 300 }, { price: 100 }, { price: 200 }].sort(byPrice); // = [{ price: 300 }, { price: 200 }, { price: 100 }]

7. 升序比较器函数

const ascending = (fn) => (a, b) => {
  const valA = fn(a);
  const valB = fn(b);
  return valA < valB ? -1 : valA > valB ? 1 : 0;
}
const byPrice = ascending(val => val.price);
[{ price: 300 }, { price: 100 }, { price: 200 }].sort(byPrice); // = [{ price: 100 }, { price: 200 }, { price: 300 }]

6. 计算两点 p1 和 p2 之间的距离

//方案1:hypot
const distance = ([x0, y0], [x1, y1]) => (
  Math.hypot(x1 - x0, y1 - y0)
);
distance([0, 1], [5, 4]); // = 5.8309518948453

5. 获取选定的文本

//方案1:getSelection
const getSelectedText = () => window.getSelection().toString();getSelectedText();

4. 生成随机数据

//随机十六进制
const randomHex = `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;  // 结果:#14f020
//随机min-max
const randomNumber = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
randomNumber(1,2);  //结果:1,2

3. 复制到剪贴板

//方案1:clipboard
const copyTextToClipboard = async (text) => { 
    await navigator.clipboard.writeText(text) 
};
copyToClipboard("Hello World");
//方案2:execCommand(支持IE浏览器)
<input id="input" type="text" value="This is the text that gets copied">
<button id="copy">Copy the text</button>
const copy = () => {
  const copyText = document.querySelector('#input')
  copyText.select()
  document.execCommand('copy')
}
document.querySelector('#copy').addEventListener('click', copy)

2. 判断元素是否在可视区域内

//方案1:getBoundingClientRect() 方法返回元素的大小及其相对于视口的位置。
function isElView(el) { 
  var top = el.getBoundingClientRect().top // 元素顶端到可见区域顶端的距离 
  var bottom = el.getBoundingClientRect().bottom // 元素底部端到可见区域顶端的距离 
  var se = document.documentElement.clientHeight // 浏览器可见区域高度。 
  if (top < se && bottom > 0) {   
    return true 
  } else if (top >= se || bottom <= 0) {  
    // 不可见 
  } 
  return false
}

1. 检测数据类型的方法

let value ='string';
Object.prototype.toString.call(value).   //'[object String]'
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容