最新公告
  • 欢迎您光临起源地模板网,本站秉承服务宗旨 履行“站长”责任,销售只是起点 服务永无止境!立即加入钻石VIP
  • 灵活运用JS开发技巧

    正文概述 掘金(远航_)   2021-07-07   407

    灵活运用JS开发技巧

    原文链接:Joway Young

    目录

    • String Skill字符串技巧
    • Number Skill数值技巧
    • Boolean Skill布尔技巧
    • Array Skill数组技巧
    • Object Skill对象技巧
    • Function Skill函数技巧
    • DOM SkillDOM技巧

    《ES6标准入门》

    String Skill

    对比时间

    const time1 = "2019-02-14 21:00:00";
    const time2 = "2019-05-01 09:00:00";
    const overtime = time1 > time2;
    // overtime => false
    

    格式化金钱

    const ThousandNum = num => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    const money = ThousandNum(20190214);
    // money => "20,190,214"
    

    生成随机ID

    const RandomId = len => Math.random().toString(36).substr(3, len);
    const id = RandomId(10);
    // id => "jg7zpgiqva"
    

    生成随机HEX色值

    const RandomColor = () => "#" + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0");
    const color = RandomColor();
    // color => "#f03665"
    

    生成星级评分

    const StartScore = rate => "★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate);
    const start = StartScore(3);
    // start => "★★★"
    

    操作URL查询参数

    const params = new URLSearchParams(location.search.replace(/\?/ig, "")); // location.search = "?name=young&sex=male"
    params.has("young"); // true
    params.get("sex"); // "male"
    

    Number Skill

    取整

    const num1 = ~~ 1.69;
    const num2 = 1.69 | 0;
    const num3 = 1.69 >> 0;
    // num1 num2 num3 => 1 1 1
    

    补零

    const FillZero = (num, len) => num.toString().padStart(len, "0");
    const num = FillZero(169, 5);
    // num => "00169"
    

    转数值

    const num1 = +null;
    const num2 = +"";
    const num3 = +false;
    const num4 = +"169";
    // num1 num2 num3 num4 => 0 0 0 169
    

    时间戳

    const timestamp = +new Date("2019-02-14");
    // timestamp => 1550102400000
    

    精确小数

    const RoundNum = (num, decimal) => Math.round(num * 10 ** decimal) / 10 ** decimal;
    const num = RoundNum(1.69, 1);
    // num => 1.7
    

    判断奇偶

    const RoundNum = (num, decimal) => Math.round(num * 10 ** decimal) / 10 ** decimal;
    const num = RoundNum(1.69, 1);
    // num => 1.7
    

    取最小最大值

    const arr = [0, 1, 2];
    const min = Math.min(...arr);
    const max = Math.max(...arr);
    // min max => 0 2
    

    生成范围随机数

    const RandomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
    const num = RandomNum(1, 10);
    

    Boolean Skill

    短路运算

    const a = d && 1; // 满足条件赋值:取假运算,从左到右依次判断,遇到假值返回假值,后面不再执行,否则返回最后一个真值
    const b = d || 1; // 默认赋值:取真运算,从左到右依次判断,遇到真值返回真值,后面不再执行,否则返回最后一个假值
    const c = !d; // 取假赋值:单个表达式转换为true则返回false,否则返回true
    

    判断数据类型

    可判断类型:undefined、null、string、number、boolean、array、object、symbol、date、regexp、function、asyncfunction、arguments、set、map、weakset、weakmap
    
    function DataType(tgt, type) {
        const dataType = Object.prototype.toString.call(tgt).replace(/\[object (\w+)\]/, "$1").toLowerCase();
        return type ? dataType === type : dataType;
    }
    DataType("young"); // "string"
    DataType(20190214); // "number"
    DataType(true); // "boolean"
    DataType([], "array"); // true
    DataType({}, "array"); // false
    

    是否为空数组

    const arr = [];
    const flag = Array.isArray(arr) && !arr.length;
    // flag => true
    

    是否为空对象

    const obj = {};
    const flag = DataType(obj, "object") && !Object.keys(obj).length;
    // flag => true
    

    满足条件时执行

    const flagA = true; // 条件A
    const flagB = false; // 条件B
    (flagA || flagB) && Func(); // 满足A或B时执行
    (flagA || !flagB) && Func(); // 满足A或不满足B时执行
    flagA && flagB && Func(); // 同时满足A和B时执行
    flagA && !flagB && Func(); // 满足A且不满足B时执行
    

    为非假值时执行

    const flag = false; // undefined、null、""、0、false、NaN
    !flag && Func();
    

    数组不为空时执行

    const arr = [0, 1, 2];
    arr.length && Func();
    

    对象不为空时执行

    const obj = { a: 0, b: 1, c: 2 };
    Object.keys(obj).length && Func();
    

    函数退出代替条件分支退出

    if (flag) {
        Func();
        return false;
    }
    // 换成
    if (flag) {
        return Func();
    }
    

    switch/case 使用区间

    const age = 26;
    switch (true) {
        case isNaN(age):
            console.log("not a number");
            break;
        case (age < 18):
            console.log("under age");
            break;
        case (age >= 18):
            console.log("adult");
            break;
        default:
            console.log("please set your age");
            break;
    }
    

    Array Skill

    克隆数组

    const _arr = [0, 1, 2];
    const arr = [..._arr];
    // arr => [0, 1, 2]
    

    合并数组

    const arr1 = [0, 1, 2];
    const arr2 = [3, 4, 5];
    const arr = [...arr1, ...arr2];
    // arr => [0, 1, 2, 3, 4, 5];
    

    去重数组

    const arr = [...new Set([0, 1, 1, null, null])];
    // arr => [0, 1, null]
    

    混淆数组

    const arr = [0, 1, 2, 3, 4, 5].slice().sort(() => Math.random() - .5);
    // arr => [3, 4, 0, 5, 1, 2]
    

    清空数组

    const arr = [0, 1, 2];
    arr.length = 0;
    // arr => []
    

    截断数组

    const arr = [0, 1, 2]
    arr.length = 2;
    // arr => [0, 1]
    

    交换赋值

    let a = 0;
    let b = 1;
    [a, b] = [b, a];
    // ab => 1 0
    

    过滤空值

    const arr = [undefined, null, "", 0, false, NaN, 1, 2].filter(Boolean);
    // arr => [1, 2]
    

    异步累计

    async function Func(deps) {
        return deps.reduce(async(t, v) => {
            const dep = await t;
            const version = await Todo(v);
            dep[v] = version;
            return dep
        }, Promise.resolve({}));
    }
    
    const result = await Func(); // 需要async 包围下使用
    

    数组首部插入成员

    let arr = [1, 2]; // 以下方法任选一种
    arr.unshift(0);
    arr = [0].concat(arr);
    arr = [0,...arr];
    // arr => [0, 1, 2]
    

    数组尾部插入成员

    let arr = [0, 1]; // 以下方法任选一种
    arr.push(2);
    arr.concat(2);
    arr[arr.length] = 2;
    arr = [...arr, 2];
    // arr => [0, 1, 2]
    

    统计数组成员个数

    const arr = [0, 1, 1, 2, 2, 2];
    const count = arr.reduce((t, v) => {
        t[v] = t[v] ? ++[v] : 1;
        return t;
    },{});
    // count => { 0: 1, 1: 2, 2: 3 }
    

    解构数组成员嵌套

    const arr = [0, 1, [2, 3, [4, 5]]];
    const [a, b, [c, d, [e, f]]] = arr;
    // a b c d e f => 0 1 2 3 4 5
    

    结构数组成员别名

    const arr = [0, 1, 2];
    const { 0: a, 1: b, 2: c } = arr
    // a b c => 0 1 2
    

    结构数组成员默认值

    const arr = [0, 1, 2];
    const [a, b, c = 3, d = 4] = arr;
    // a b c d => 0 1 2 4
    

    获取随机数成员

    const arr = [1, 2, 3, 4, 5];
    const randomItem = arr[Math.floor(Math.random() * arr.length)];
    // randomItem => 1
    

    创建指定长度数组

    const arr = [...new Array(3).keys()];
    // arr => [0, 1, 2]
    

    创建指定长度且值相等的数组

    const arr = new Array(3).fill(0);
    // arr => [0, 0, 0]
    

    reduce代替map和filter

    const _arr = [0, 1, 2];
    
    // map
    const arr = _arr.map(v => v * 2);
    const arr = _arr.reduce((t, v) => {
        t.push(v * 2);
        return t;
    }, []);
    // arr => [0, 2, 4]
    
    // filter
    const arr = _arr.filter(v => v > 0);
    const arr = _arr.reduce((t, v) => {
        v > 0 && t.push(v);
        return t;
    }, []);
    // arr => [1, 2]
    
    // map 和 filter
    const arr = _arr.map(v => v * 2).filter(v => v > 2);
    const arr = _arr.reduce((t, v) => {
        v = v * 2;
        v > 2 && t.push(v);
        return t;
    }, []);
    // arr => [4]
    

    Object Skill

    克隆对象

    const _obj = { a: 0, b: 1, c: 2 };
    const obj = { ..._obj };
    const obj = JSON.parse(JSON.stringify(_obj));
    // obj => { a: 0, b: 1, c: 2 }
    

    合并对象

    const obj1 = { a: 0, b: 1, c: 2 };
    const obj2 = { c: 3, d: 4, e: 5 };
    const obj = { ...obj1, ...obj2 };
    // obj => { a: 0, b: 1, c: 3, d: 4, e: 5 }
    

    对象字面量

    const env = "prod";
    const link = {
        dev: "Development Address",
        test: "Testing Address",
        prod: "Production Address"
    }[env];
    
    // link => "Production Address"
    

    对象变量属性

    const flag = false;
    const obj = {
        a: 0,
        b: 1,
        [flag ? "c" : "d"]: 2
    };
    // obj => { a: 0, b: 1, d: 2 }
    

    创建纯空对象

    const obj = Object.create(null);
    Object.prototype.a = 0;
    // obj => {}
    

    删除对象无用属性

    const obj = { a: 0, b: 1, c: 2 }; // 只想拿b和c
    const { a, ...rest } = obj;
    // rest => { b: 1, c: 2 }
    

    解构对象属性嵌套

    const obj = { a: 0, b: 1, c: { d: 2, e: 3 } };
    const { c: { d, e } } = obj;
    // d e => 2 3
    

    解构对象属性别名

    const obj = { a: 0, b: 1, c: 2 };
    const { a, b: d, c: e } = obj;
    // a d e => 0 1 2
    

    解构对象属性默认值

    const obj = { a: 0, b: 1, c: 2 };
    const { a, b = 2, d = 3} = obj;
    // a b d => 0 1 3
    

    Function Skill

    函数自执行

    const Func = function() {}(); // 常用
    
    (function() {})(); // 常用
    (function() {}()); // 常用
    [function() {}()];
    
    + function() {}();
    - function() {}();
    ~ function() {}();
    ! function() {}();
    
    new function() {};
    new function() {}();
    void function() {}();
    typeof function() {}();
    delete function() {}();
    
    1, function() {}();
    1 ^ function() {}();
    1 > function() {}();
    

    隐式函数返回值

    const Func = function(name) {
        return "I Love " + name
    }
    
    // 换成
    const Func = name => "I Love " + name;
    

    一次性函数

    function Func() {
        console.log("x")
        Func = function() {
            console.log("y")
        }
    }
    

    惰性载入函数

    function Func() {
        if (a === b){
            console.log("x");
        }else {
            console.log("Y");
        }
    }
    
    // 换成
    function Func() {
        if(a === b) {
            Func = function() {
                console.log("x")
            }
        }else {
            Func = function() {
                console.log("y")
            }
        }
        return Func();
    }
    

    检测非空参数

    function IsRequired() {
        throw new Error("param is required");
    }
    function Func(name = IsRequired()) {
        console.log("I Love" + name)
    }
    Func(); // "param is required"
    Func("You") // "I Love You"
    

    字符串创建函数

    const Func = new Function("name", "console.log(\"I Love \" + name)");
    

    优雅处理错误信息

    try {
        Func();
    } catch (e) {
        location.href = "https://stackoverflow.com/search?q=[js]+" + e.message;
    }
    

    优雅处理 Async/ Await 参数

    function AsyncTo(promise) {
        return promise.then(data => [null, data]).catch(err => [err]);
    }
    const [err, res] = await AsyncTo(Func());
    

    优雅处理多个函数返回值

    function Func() {
        return Promise.all([
            fetch("/user"),
            fetch("/comment")
        ])
    }
    
    const [user, comment] = await Func(); // 需在async 包围下使用
    

    DOM Skill

    显示全部DOM边框

    [].forEach.call($$("*"), dom => {
        dom.style.outline = "1px solid #" + (~~(Math.random() * (1 << 24))).toString(16);
    });
    

    自适应页面

    function AutoResponse(width = 750) {
        const target = document.documentElement;
        target.clientWidth >= 600
            ? (target.style.fontSize = "80px")
            : (target.style.fontSize = target.clientWidth / width * 100 + "px");
    }
    

    过滤XSS

    function FilterXss(content) {
        let elem = document.createElement("div");
        elem.innerText = content;
        const result = elem.innerHTML;
        elem = null;
        return result;
    }
    

    存取LocalStorage

    localStorage.setItem("love", JSON.stringify("I Love You"));
    const love = JSON.parse(localStorage.getItem("love"));
    
    (_=>[..."`1234567890-=~~QWERTYUIOP[]\\~ASDFGHJKL;'~~ZXCVBNM,./~"].map(x=>(o+=`/${b='_'.repeat(w=x<y?2:' 667699'[x=["Bs","Tab","Caps","Enter"][p++]||'Shift',p])}\\|`,m+=y+(x+'    ').slice(0,w)+y+y,n+=y+b+y+y,l+=' __'+b)[73]&&(k.push(l,m,n,o),l='',m=n=o=y),m=n=o=y='|',p=l=k=[])&&k.join`
    `)()
    

    起源地下载网 » 灵活运用JS开发技巧

    常见问题FAQ

    免费下载或者VIP会员专享资源能否直接商用?
    本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
    提示下载完但解压或打开不了?
    最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,若小于网盘提示的容量则是这个原因。这是浏览器下载的bug,建议用百度网盘软件或迅雷下载。若排除这种情况,可在对应资源底部留言,或 联络我们.。
    找不到素材资源介绍文章里的示例图片?
    对于PPT,KEY,Mockups,APP,网页模版等类型的素材,文章内用于介绍的图片通常并不包含在对应可供下载素材包内。这些相关商业图片需另外购买,且本站不负责(也没有办法)找到出处。 同样地一些字体文件也是这种情况,但部分素材会在素材包内有一份字体下载链接清单。
    模板不会安装或需要功能定制以及二次开发?
    请QQ联系我们

    发表评论

    还没有评论,快来抢沙发吧!

    如需帝国cms功能定制以及二次开发请联系我们

    联系作者

    请选择支付方式

    ×
    迅虎支付宝
    迅虎微信
    支付宝当面付
    余额支付
    ×
    微信扫码支付 0 元