5分钟掌握JavaScript小技巧

译者按: 技巧虽好、重在掌握并使用起来!javascript

为了保证可读性,本文采用意译而非直译。另外,本文版权归原做者全部,翻译仅用于学习。java

clipboard.png

1. 删除数组尾部元素

一个简单的用来清空或则删除数组尾部元素的简单方法就是改变数组的length属性值。小程序

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

2.使用对象解构来模拟命名参数

若是你须要将一系列可选项做为参数传入函数,那么你也许倾向于使用了一个对象(Object)来定义配置(Config)。微信小程序

doSomething({ foo: 'Hello', bar: 'Hey!', baz: 42 });
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 : 13;
      // ...
}

这是一个陈旧、可是颇有效的方法,它模拟了JavaScript中的命名参数。不过呢,在doSomething中处理config的方式略显繁琐。在ES2015中,你能够直接使用对象解构。数组

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

若是你想让这个参数是可选的,也很简单。微信

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

3. 使用对象解构来处理数组

可使用对象解构的语法来获取数组的元素:less

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

4. 在switch语句中用范围值

可使用下面的技巧来写知足范围值的switch语句:async

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. await多个async函数

在使用async/await的时候,可使用Promise.all来await多个async函数。函数

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

6. 建立一个纯(pure)对象

你能够建立一个100%的纯对象,他不从Object中继承任何属性或则方法(好比,constructortoString()等等)。学习

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

7. 格式化JSON代码

JSON.stringify不止能够将一个对象字符化,还能够格式化输出JSON对象。

const obj = { 
  foo: { bar: [11, 22, 33, 44], baz: { bing: true, boom: 'Hello' } } 
};
// The third parameter is the number of spaces used to 
// beautify the JSON output.
JSON.stringify(obj, null, 4); 
// =>"{
// =>    "foo": {
// =>        "bar": [
// =>            11,
// =>            22,
// =>            33,
// =>            44
// =>        ],
// =>        "baz": {
// =>            "bing": true,
// =>            "boom": "Hello"
// =>        }
// =>    }
// =>}"

8. 从数组中移除重复元素

ES2015中,有了集合的语法。经过使用集合语法和Spread操做,能够很容易将重复的元素移除:

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

9. 平铺多维数组

使用Spread操做,能够很容易去平铺嵌套多维数组:

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]

就这些啦!我但愿这些小技巧能够帮你写出更加漂亮的JS代码!若是还不够,那么不妨用Fundebug作你的辅助!

精选评论

  • Ethan B Martin: 这个switch的写法很巧妙,不过不推荐。请不要鼓励开发者用这种方式去写JS代码。咱们曾经有一个工程师这么写,后来在代码review的时候,形成了很大的阅读苦难。好在咱们及时将其重构为更加容易读懂的代码。不妨对比一下用swtich和if的区别:

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

    第二种写法有几点优点:
    A) 代码量更少,更加易读;B) 你不须要声明一个局部变量,读者不会一直要去追踪你如何对这个变量作了更改;C) switch(true)真的会让人莫名其妙。

  • Flo Sloot: 很棒的文章!不过不推荐第六招,除非你必定要使用。由于它的执行效率很慢,并且占用空间更大。由于V8并无对空对象作优化。

关于Fundebug

Fundebug专一于JavaScript、微信小程序、微信小游戏、支付宝小程序、React Native、Node.js和Java实时BUG监控。 自从2016年双十一正式上线,Fundebug累计处理了6亿+错误事件,获得了Google、360、金山软件等众多知名用户的承认。欢迎免费试用!

图片描述

版权声明

转载时请注明做者Fundebug以及本文地址:
https://blog.fundebug.com/201...