JavaScript 实用小技巧

删除数组尾部元素 

一个简单方法就是改变数组的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
 

使用对象解构(object destructuring)来模拟命名参数 

如果需要将一系列可选项作为参数传入函数,你很可能会使用对象(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 中的命名参数。

在 ES 2015 中,你可以直接使用对象解构:

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

让参数可选也很简单:

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

 

使用对象解构来处理数组 

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

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

 

在 Switch 语句中使用范围值

 可以这样写满足范围值的语句:

 1 function getWaterState(tempInCelsius) {
 2   let state;
 3   
 4   switch (true) {
 5     case (tempInCelsius <= 0):
 6       state = 'Solid';
 7       break;
 8     case (tempInCelsius > 0 && tempInCelsius < 100):
 9       state = 'Liquid';
10       break;
11     default:
12       state = 'Gas';
13   }
14   return state;
15 }

 

await 多个 async 函数 

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

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

 

创建 pure objects/ 

你可以创建一个 100% pure object,它不从Object中继承任何属性或则方法(比如constructor, 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

 

格式化 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 // =>}"

 

从数组中移除重复元素 

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

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

 

平铺多维数组 

使用 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 
7 const arr = [11, [22, 33], [44, [55, 66, [77, [88]], 99]]];
8 const flatArr = flattenArray(arr);
9 //=> [11, 22, 33, 44, 55, 66, 77, 88, 99]

 

posted @ 2019-09-03 10:02  ommph  阅读(141)  评论(0编辑  收藏  举报