分享10 个 JS 实用的小技巧

目录
文章目录隐藏
  1. 利用 new URL 解析 URL
  2. 一行代码实现星级评分
  3. 同步阻塞法实现 sleep 函数
  4. 判断是否是千分符字符
  5. 用位运算提升效率
  6. 一行代码生成指定长度的数组
  7. 判断数据类型
  8. 复制文本到剪切板
  9. 正则匹配可以只有 0 但开头不能是 0 的数字
  10. 正则判断字符重复次数不超过两次

分享 10 个 JS 实用的小技巧

JavaScript 小技巧,几个不错的知识点,方便学习 js 的朋友,感觉内容非常不错特分享一下,需要的朋友可以参考下。

利用 new URL 解析 URL

const parseURL = (url = '') => {
    const res = new URL(url);
    res.queryParams = key => {
        if (key) {
           return res.searchParams.get(key)
        };
        const params = {};
        const paramGroup = res.search.replace(/^\?/,'').split('&');
        paramGroup.forEach(param => {
            const [key, val] = param.split('=');
            params[key] = val;
        });
        return params;
    };
    return res;
};
parseURL('https://www.你的网址.com/a/b?c=1&d=2');

一行代码实现星级评分

const getRate = (rate = 0) => '★★★★★☆☆☆☆☆'.slice(5 - rate, 10 - rate);
getRate(3);

同步阻塞法实现 sleep 函数

const sleep = delay => {
    const start = new Date().getTime();
    while (new Date().getTime() < start + delay) {
       continue;
    };
};
console.log(1);
sleep(3000);
console.log(2);

判断是否是千分符字符

const numberIsThousand = str => /^-?\d{1,3}(,\d{3})*(\.\d+)?$/.test(str);
numberIsThousand('100,000,000,000') // true
numberIsThousand('100,000,000,00') // false

用位运算提升效率

// | 取整
let num1 = 1.7;
num1 = num1 | 0;

// >> 取半
let num2 = 6;
num2 = num2 >> 1; // 3

// << 加倍
let num3 = 6;
num3 = num3 << 1; // 12

// ^ 交换值
let num4 = 10;
let num5 = 20;

num4 ^= num5;
num5 ^= num4;
num4 ^= num5; // num4 === 2, num5 === 1

// & 判断奇数
let num6 = 10;
let num7 = 11;
num6 & 1 === 1; // true
num7 & 1 === 1; // false

// ~ 判断是否存在
const data = '123456';
const key = '3';
const keyIsExist = !!~data.indexOf(key); // true

// 是否 2 的整数幂
const isPowerOf2 = num => (num & (num - 1)) === 0;
isPowerOf2(8) // true
isPowerOf2(7) // false

一行代码生成指定长度的数组

const List = len => [...new Array(len).keys()];
const list = List(10); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

判断数据类型

const type = data => {
      let toString = Object.prototype.toString;
      const dataType =
        data instanceof Element
          ? 'element' // 为了统一 DOM 节点类型输出
          : toString
              .call(data)
              .replace(/\[object\s(.+)\]/, '$1')
              .toLowerCase()
      return dataType
};

type({}); // object

复制文本到剪切板

const copyToClipboard = content => {
    const clipboardData = window.clipboardData;
    if (clipboardData) {
        clipboardData.clearData();
        clipboardData.setData('Text', content);
        return true;
    } else if (document.execCommand) {
        const el = document.createElement('textarea');
        el.value = content;
        el.setAttribute('readonly', '');
        el.style.position = 'absolute';
        el.style.left = '-9999px';
        document.body.appendChild(el);
        el.select();
        document.execCommand('copy');
        document.body.removeChild(el);
        return true;
    }
    return false;
};
copyToClipboard('hello world');

正则匹配可以只有 0 但开头不能是 0 的数字

const getCorrectNumber = (str = '') => /^(\d|[1-9]\d*)$/.test(str);
getCorrectNumber('0'); // true
getCorrectNumber('011'); // false
getCorrectNumber('101'); // true

正则判断字符重复次数不超过两次

const strIsRepeatThan2 = (str = '') => /^(?!.*(.).*\1{2})[\da-zA-Z].+$/.test(str);
strIsRepeatThan2('123456'); // true
strIsRepeatThan2('1234566'); // true
strIsRepeatThan2('12345666'); // false

本文完,感谢阅读,如果大家有更好的 js 小技巧,欢迎留言一起学习。

推荐阅读更多使用的 JS 小技巧:

10 个对 js 开发有帮助的小技巧

前端开发实用的 js 正则表达式小技巧总结

提升代码质量的 Javascript 小技巧,你值得拥有!

10 个 JavaScript 开发必须会的实用小技巧

「点点赞赏,手留余香」

0

给作者打赏,鼓励TA抓紧创作!

微信微信 支付宝支付宝

还没有人赞赏,快来当第一个赞赏的人吧!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » 分享10 个 JS 实用的小技巧

发表回复