5分钟,掌握9个风骚又简洁的JavaScript技巧

2,705 阅读3分钟
原文链接: zhuanlan.zhihu.com

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. 用解构对象来模拟命名函数

当你需要将一组变量作为参数传递给某个函数时,使用「配置对象」的可能性很高,如下所示:

  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. }

使用doSomething函数的时候, { foo: 'Hello', bar: 'Hey!', baz: 42 } 这个 Json 作为参数传递了进来,然后在函数中拆解Json给变量赋值。

这是一种古老而有效的模式,它试图模拟 JavaScript中的命名参数。这样处理虽然也行,但是会导致代码不必要的冗长。 借助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(',');

数组中的第2项「US」赋值给了country,第四项「New York」赋值给了state。

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.多个异步函数的异步回调机制

可通过 Promise.all 来等待多个异步函数完成。

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

6.创造纯净的对象

你可以创造100%纯净的对象,它不会从Object类继承任何方法(例如:构造函数、toString() 等)。

  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对象变成字符串,也可以用它美化你的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.从数组中删除重复的项目

通过包含Spread运算符的ES2015——也就是最新的JS,你可以很容易地从数组中删除重复的项目

  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]

以上就是9个小技巧啦,希望它们能帮助你写出更好更漂亮的JS代码!


零基础成为高薪前端工程师!从零开始跟随 Google、GitHub 学习【前端开发】硅谷课程,挑战原汁原味的硅谷项目,获得硅谷认证证书,点击立即免费体验

web前端开发技术学习_前端开发工程师培训_前端开发入门/进阶课程-优达学城(Udacity)官网 | Udacity