美文网首页
七个实用的JavaScript技巧

七个实用的JavaScript技巧

作者: 云凡的云凡 | 来源:发表于2020-12-28 18:36 被阅读0次

    1、获取数组的唯一值 (Get Unique Values of an Array)
    获取唯一值数组可能比想象的要容易:

    var j = [...new Set([1, 2, 3, 3])]
    >> [1, 2, 3]
    

    2、数组和布尔 (Array and Boolean)
    是否曾经需要从数组中过滤出伪造的值 ( 0 , undefined , null , false等)?你可能不知道此技巧:

    myArray
        .map(item => {
            // ...
        })
        // Get rid of bad values
        .filter(Boolean);
    

    只需传递Boolean ,所有那些虚假的值就会消失!

    3、创建空对象 (Create Empty Objects)
    当然,你可以使用{}创建一个似乎为空的对象,但是该对象仍然具有proto以及通常的hasOwnProperty和其他对象方法。但是,有一种方法可以创建一个纯“字典”对象 :

    let dict = Object.create(null);
     
    // dict.__proto__ === "undefined"
    // No object properties exist until you add them
    

    没有放置在该对象上的键或方法绝对没有!

    4、合并物件 (Merge Objects)
    在JavaScript中合并多个对象的需求一直存在,尤其是在我们开始创建带有选项的类和小部件时:

    const person = { name: 'David Walsh', gender: 'Male' };
    const tools = { computer: 'Mac', editor: 'Atom' };
    const attributes = { handsomeness: 'Extreme', hair: 'Brown', eyes: 'Blue' };
     
    const summary = {...person, ...tools, ...attributes};
    /*
    Object {
      "computer": "Mac",
      "editor": "Atom",
      "eyes": "Blue",
      "gender": "Male",
      "hair": "Brown",
      "handsomeness": "Extreme",
      "name": "David Walsh",
    }
    */
    

    这三个点使任务变得如此简单!

    5、需要功能参数 (Require Function Parameters)
    能够为函数参数设置默认值是对JavaScript的一个很棒的补充,但是请查看以下技巧, 要求为给定参数传递值 :

    const isRequired = () => { throw new Error('param is required'); };
     
    const hello = (name = isRequired()) => { console.log(`hello ${name}`) };
     
    // This will throw an error because no name is provided
    hello();
     
    // This will also throw an error
    hello(undefined);
     
    // These are good!
    hello(null);
    hello('David');
    

    这是一些下一级的验证和JavaScript的用法!

    6、破坏别名 (Destructuring Aliases)
    销毁是JavaScript的一个非常受欢迎的附加功能,但是有时我们希望用另一个名称来引用这些属性,因此我们可以利用别名:

    const obj = { x: 1 };
     
    // Grabs obj.x as { x }
    const { x } = obj;
     
    // Grabs obj.x as { otherName }
    const { x: otherName } = obj;
    

    有助于避免与现有变量的命名冲突!

    7、获取查询字符串参数 (Get Query String Parameters)
    多年以来,我们编写了粗糙的正则表达式来获取查询字符串值,但是日子已经一去不复返了
    输入URLSearchParams API:

    var urlParams = new URLSearchParams(window.location.search);
     
    console.log(urlParams.has('post')); // true
    console.log(urlParams.get('action')); // "edit"
    console.log(urlParams.getAll('action')); // ["edit"]
    console.log(urlParams.toString()); // "?post=1234&action=edit"
    console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"
    

    将这些技巧保存在工具箱中,已备需要时使用吧!
    文章翻译自: https://davidwalsh.name/javascript-tricks

    相关文章

      网友评论

          本文标题:七个实用的JavaScript技巧

          本文链接:https://www.haomeiwen.com/subject/arprnktx.html