5分钟掌握JavaScript小技巧

1. 删除数组尾部元素

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

 
  1. const arr = [11, 22, 33, 44, 55, 66];

  2. // truncanting

  3. arr.length = 3;

  4. console.log(arr); //=> [11, 22, 33]

  5. // clearing

  6. arr.length = 0;

  7. console.log(arr); //=> []

  8. console.log(arr[2]); //=> undefined

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

如果你需要将一系列可选项作为参数传入函数,那么你也许倾向于使用了一个对象(Object)来定义配置(Config)。

 
  1. doSomething({ foo: 'Hello', bar: 'Hey!', baz: 42 });

  2. function doSomething(config) {

  3.    const foo = config.foo !== undefined ? config.foo : 'Hi';

  4.    const bar = config.bar !== undefined ? config.bar : 'Yo!';

  5.      const baz = config.baz !== undefined ? config.baz : 13;

  6.      // ...

  7. }

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

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

  2.  // ...

  3. }

如果你想让这个参数是可选的,也很简单。

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

  2.  // ...

  3. }

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

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

 
  1. const csvFileLine = '1997,John Doe,US,john@doe.com,New York';

  2. const { 2: country, 4: state } = csvFileLine.split(',');

4. 在switch语句中用范围值

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

 
  1. function getWaterState(tempInCelsius) {

  2.  let state;

  3.  switch (true) {

  4.    case (tempInCelsius <= 0):

  5.      state = 'Solid';

  6.      break;

  7.    case (tempInCelsius > 0 && tempInCelsius < 100):

  8.      state = 'Liquid';

  9.      break;

  10.    default:

  11.      state = 'Gas';

  12.  }

  13.  return state;

  14. }

5. await多个async函数

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

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

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

你可以创建一个100%的纯对象,他不从 Object中继承任何属性或则方法(比如, constructortoString()等等)。

 
  1. const pureObject = Object.create(null);

  2. console.log(pureObject); //=> {}

  3. console.log(pureObject.constructor); //=> undefined

  4. console.log(pureObject.toString); //=> undefined

  5. console.log(pureObject.hasOwnProperty); //=> undefined

7. 格式化JSON代码

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

 
  1. const obj = {

  2.  foo: { bar: [11, 22, 33, 44], baz: { bing: true, boom: 'Hello' } }

  3. };

  4. // The third parameter is the number of spaces used to

  5. // beautify the JSON output.

  6. JSON.stringify(obj, null, 4);

  7. // =>"{

  8. // =>    "foo": {

  9. // =>        "bar": [

  10. // =>            11,

  11. // =>            22,

  12. // =>            33,

  13. // =>            44

  14. // =>        ],

  15. // =>        "baz": {

  16. // =>            "bing": true,

  17. // =>            "boom": "Hello"

  18. // =>        }

  19. // =>    }

  20. // =>}"

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

ES2015中,有了集合的语法。通过使用集合语法和Spread操作,可以很容易将重复的元素移除:

 
  1. const removeDuplicateItems = arr => [...new Set(arr)];

  2. removeDuplicateItems([42, 'foo', 42, 'foo', true, true]);

  3. //=> [42, "foo", true]

9. 平铺多维数组

使用Spread操作,可以很容易去平铺嵌套多维数组:

 
  1. const arr = [11, [22, 33], [44, 55], 66];

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

可惜,上面的方法仅仅适用于二维数组。不过,通过递归,我们可以平铺任意维度的嵌套数组。

 
  1. function flattenArray(arr) {

  2.  const flattened = [].concat(...arr);

  3.  return flattened.some(item => Array.isArray(item)) ?

  4.    flattenArray(flattened) : flattened;

  5. }

  6. const arr = [11, [22, 33], [44, [55, 66, [77, [88]], 99]]];

  7. const flatArr = flattenArray(arr);

  8. //=> [11, 22, 33, 44, 55, 66, 77, 88, 99]

就这些啦!我希望这些小技巧可以帮你写出更加漂亮的JS代码!

精选评论

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

 
  1. function getWaterState1(tempInCelsius) {

  2.  let state;

  3.  switch (true) {

  4.    case (tempInCelsius <= 0):

  5.      state = 'Solid';

  6.      break;

  7.    case (tempInCelsius < 100):

  8.      state = 'Liquid';

  9.      break;

  10.    default:

  11.      state = 'Gas';

  12.  }

  13.  return state;

  14. }

  15. function getWaterState2(tempInCelsius) {

  16.  if (tempInCelsius <= 0) {

  17.    return 'Solid';

  18.  }

  19.  if (tempInCelsius < 100) {

  20.    return 'Liquid';

  21.  }

  22.  return 'Gas';

  23. }

第二种写法有几点优势:

A) 代码量更少,更加易读;

B) 你不需要声明一个局部变量,读者不会一直要去追踪你如何对这个变量做了更改;

C) switch(true)真的会让人莫名其妙。

Flo Sloot: 很棒的文章!不过不推荐第六招,除非你一定要使用。因为它的执行效率很慢,而且占用空间更大。因为V8并没有对空对象做优化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_35430208

您的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值