Learn these neat JavaScript tricks

花费 5 分钟就能学会 JavaScript 的这些小技巧,希望能帮助到你

1、清空或截断数组
      在没有重新分配一个数组的情况下用简单的方式清空或截断一个数组,通过改变它的长度属性值。

    const arr = [11, 22, 33, 44, 55, 66];
    //截取
    arr.length = 3;
    console.log(arr); //=> [11, 22, 33]
    //清空
    arr.length = 0;
    console.log(arr); //=> []
    console.log(arr[2]); //=> undefined

2、用对象解析解构赋值模拟命名参数
      当你需要传递一个传递一组可变的变量给一个函数, 很可能你已经使用配置对象,就像这样:

    doSomething({ foo: 'Hello', bar: 'Hey!', baz: 42 });
    function doSomething(config) {
        const foo = config.foo || 'Hi';
        const bar = config.bar || 'Yo!';
        const baz = config.baz || 13;
        // ...
    }

      这是一个古老但是有效的模式, 在JavaScript中被用来模拟命名参数,函数调用看起来不错。在另一方面,这样配置对象显得繁琐。使用ES2015解构赋值,你可以避免这个缺点。

    function doSomething({ foo = 'Hi', bar = 'Yo!', baz: 13 }) {
        // ...
    }

      如果你需要配置可选的参数,也非常容易:

    function doSometing({ foo = 'Hi', bar = 'Yo!', baz = 13 } = {}) {
        // ...
    }

      如果有些参数是必传的,可以这样来实现:

    function requiredParam (param) {
        const requiredParamError = new Error(
            `Required parameter, "${param}" is missing.`
        )
        //preserve original stack trace
        if (typeof Error.captureStackTrace === 'function') {
            Error.captureStackTrace(
                requiredParamError,
                requiredParam
            )
        }
        throw requiredParamError
    }

      然后

    function doSomething({ role = requiredParam('role'), withContactInfo } = {})
    doSomething({withContactInfo: true})

      这样使用就会报错Required parameter, “role” is missing.代表role是必传的。
3、在数组项中使用对象解构赋值
      使用对象解构赋值将数组香指定为单个对象

    const csvFileLine = 'hello, Hu, China, xiaohu@doe.com, SiChuan';
    const { 2: country, 4: state } = csvFileLine.split(',')

4、在Switch中使用范围
      这是一个简单的技巧在switch语句中使用范围:

    function getWaterState(tempInCelsius) {
        let state;
        switch (true) {
            case (tempInCelsius <= 0):
                state = 'Solid';
                break;
            case (tempInCelsius > 0 && tempInCelsius < 100):
                state = 'Liquid';
                break;
            default:
                state = 'Gas';
        }
        return state;
    }

5、创建纯的对象
      你可以创建一个100%纯的对象,它不会从对象中继承任何的属性或方法(例如:constructor, toString() ....).

    const pureObject = Object.create(null);
    console.log(pureObject); //=> {}
    console.log(pureObject.constructor); //=> undefined
    console.log(pureObject.toString); //=> undefined
    console.log(pureObject.hasOwnProperty); //=> undefined

6、格式化JSON代码
      JSON.stringify能做的不仅仅把一个对象格式化为一个对象,你也可以美化你的JSON输出:

    const obj = {
        foo: { bar: [11, 22, 33, 44], baz: { bing: true, boom: 'Hello' } };
    }
    //第三个参数是缩进的数字,返回值文本在每个级别缩进指定数目的空格
    JSON.stringify(obj, null, 4);
    // =>"{
    // =>    "foo": {
    // =>        "bar": [
    // =>            11,
    // =>            22,
    // =>            33,
    // =>            44
    // =>        ],
    // =>        "baz": {
    // =>            "bing": true,
    // =>            "boom": "Hello"
    // =>        }
    // =>    }
    // =>}"

7、从一个数组中去除重复项
      通过使用ES2015的Set与展开运算符,可以很容易从一个数组中去除重复的项:

    const removeDuplicateItems = arr = [...new Set(arr)];
    removeDuplicateItems([42, 'foo', 42, 'foo', true, true]);
    //=> [42, 'foo', true]

8、多维数组一维化
      使用展开运算符一维化数组:

    const arr = [11, [22, 33], [44, 55], 66];
    const flatArr = [].concat(...arr); //=> [11, 22, 33, 44, 55, 66]

      不幸的是上面的技巧只能用于二维数组,但是使用递归调用,使它适用于二维以上的数组:

    function flattenArray(arr) {
        const flattened = [].concat(...arr);
        return flattened.some(item => Array.isArray(item)) ? flattenArray(flattened) : flattened;
    }
    const arr = [11, [22, 33], [44, [55, 66, [77, [88]], 99]]];
    const flatArr = flattenArray(arr);
    //=> [11, 22, 33, 44, 55, 66, 77, 88, 99]

参考链接
      Learn these neat JavaScript tricks in less than 5 minutes  by Alcides Queiroz

相关文章

仅有 1 条评论
  1. shilunqiang

    学到了一些,写的挺仔细的哈,博主加油↖(^ω^)↗

    shilunqiang

此处评论已关闭