1.清除或截断数组

清除或截断数组而不重新分配数组的一种简单方法是通过改变其长度属性值:

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。用对象破坏模拟命名参数

当您需要将一组可变选项传递给某个函数时,很可能已经使用了配置对象,比如:

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中的命名参数。函数调用看起来很好。另一方面,配置对象处理逻辑是不必要冗长的。用ES2015对象破坏,你可以规避这个缺点:

This is an old but effective pattern, which tries to simulate named parameters in JavaScript. The function calling looks fine. On the other hand, the config object handling logic is unnecessarily verbose. With ES2015 object destructuring, you can circumvent this downside:

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

如果你需要使配置对象是可选的,那么它也是非常简单的:

And if you need to make the config object optional, it’s very simple, too:

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

 

三。数组项目的对象破坏 Object destructuring for array items

用对象分解将数组项分配给单个变量:

Assign array items to individual variables with object destructuring:

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

4. Switch with ranges

switch 语句中使用范围值

NOTE: After some thought, I’ve decided to differentiate this trick from the others in this article. This is NOT a time-saving technique, NOR is it suitable for real life code. Keep in mind: “If”s are always better in such situations.
Differently from the other tips in this post, it is more a curiosity than something to really use.
Anyway, I’ll keep it in this article for historical reasons.
Here’s a simple trick to use ranges in switch statements:

注:经过一番思考,我决定将这一技巧与其他文章区分开来。这不是一种省时的技术,也不适用于现实生活中的代码。记住:“如果”在这种情况下总是更好。

与这篇文章中的其他技巧不同,它更像是一种好奇心而不是真正使用的东西。

不管怎样,我将保留这篇文章的历史原因。

这里有一个简单的技巧来使用开关语句中的范围:

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 multiple async functions with async/await 用异步/等待方式等待多个异步函数

 

It’s possible to await multiple async functions to finish by using Promise.all: 可以通过使用允诺来等待多个异步函数完成:

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

 

6. Creating pure objects 创建纯对象

You can create a 100% pure object, which won’t inherit any property or method from Object (for example, constructor, toString() and so on).

您可以创建一个100%纯对象,它不会从Object继承任何属性或方法(例如,构造函数、toString()等等)。

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

 

7. Formatting JSON code 格式化JSON代码

JSON.stringify can do more than simply stringify an object. You can also beautify your JSON output with it:

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. Removing duplicate items from an array   从数组中移除重复项

By using ES2015 Sets along with the Spread operator, you can easily remove duplicate items from an array:

通过使用ES2015集和扩展运算符,可以轻松地从数组中删除重复项:

 

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

 

9. Flattening multidimensional arrays  扁平化多维数组

Flattening arrays is trivial with Spread operator:

平坦化阵列与扩展算子是微不足道的:


const arr = [11, [22, 33], [44, 55], 66];
const flatArr = [].concat(...arr); //=> [11, 22, 33, 44, 55, 66]
Unfortunately, the above trick will only work with bidimensional arrays. But with recursive calls, we can make it suitable for arrays with more than 2 dimensions:

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]
And there you have it! I hope these neat little tricks help you write better and more beautiful JavaScript.

觉得可用,就经常来吧!Javascript技巧 脚本宝典 欢迎评论哦! js技巧,巧夺天工,精雕玉琢。小宝典献丑了!