js更加简洁的小技巧(数组去重,对象解构)

1、清空或截断数组
在不重新给数组赋值的情况下,清空或截断数组的最简单方法是更改​​其 length 属性值:

const arr = [1, 2, 3, 4, 5];
// 截断
arr.length = 3;
console.log(arr); // [1, 2, 3]
// 清除
arr.length = 0;
console.log(arr); // []
console.log(arr[2]); // undefined

2、使用对象解构模拟命名参数
当需要将一组可选变量传递给某个参数时,很可能已经在使用配置对象:

    doSomething({
      foo: 'hello',
      bar: 'Hey!',
      baz: 10
    });

    function doSomething(config) {
      const foo = config.foo !== undefined ? config.foo : 'Hi';
      const bar = config.bar !== undefined ? config.bar : 'Yo!';
      const baz = config.baz !== undefined ? config.baz : 12;
      // ...
    }

这是一个比较老但有效的模式,它试图在js中模拟命名参数。函数调用看起来很好,另一方面配置对象处理逻辑不必要地冗长。使用对象解构可以绕过这个缺点:

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

3、使用对象解构来处理数组
可以使用对象解构将数组项分配给各个变量:

    const fmper = '1990, John Doe, US, John@doe.com, New York';
    const { 2: country, 4: state } = fmper.split(',');

4、使用async/await来await多个async函数

await Promise.all([anAsyncCall(), thisIsAlsoAsync(), oneMore()]);

5、创建纯(pure)对象

    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: [1, 2, 3, 4],
        baz: {
          bing: true,
          boom: 'Hello'
        }
      }
    };
    // 第三个参数代表空格间距
    JSON.stringify(obj, null, 2);
    // {
    //   "foo": {
    //     "bar": [
    //       1,
    //       2,
    //       3,
    //       4
    //     ],
    //     "baz": {
    //       "bing": true,
    //       "boom": "Hello"
    //     }
    //   }
    // }

7、数组去重
通过使用集合语法和Spread展开运算符,轻松删除数组重复项:

const arrAn = arr => [...new Set(arr)];
arrAn([1, 2, 3, 2, 'foo', 'al', 'foo', true, false, true]); // [1, 2, 3, "foo", "al", true, false]

8、平铺多维数组

const arrOne = [1, 2, [1, 3], 2, [2, 4]];
const flatArr = [].concat(...arrOne); // [1, 2, 1, 3, 2, 2, 4]

可惜上面的方法只适用于二维数组,通过递归可以平铺任意维度的数组:

    function flattenArray(arr) {
      const flattened = [].concat(...arr);
      return flattened.some(item => Array.isArray(item)) ? flattenArray(flattened) : flattened;
    }

    const arr1 = [1, [2, 3], [4, [5, 6, [7, 8]]], 9];
    const arr2 = flattenArray(arr1); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值