精巧笔驱动_在不到5分钟的时间内学习这些精巧JavaScript技巧

精巧笔驱动

by Alcides Queiroz

通过Alcides Queiroz

在不到5分钟的时间内学习这些精巧JavaScript技巧 (Learn these neat JavaScript tricks in less than 5 minutes)

专业人士使用的省时技术 (Time-saving techniques used by pros)
1.清除或截断数组 (1. Clearing or truncating an array)

An easy way of clearing or truncating an array without reassigning it is by changing its length property value:

清除或截断数组而不重新分配数组的一种简单方法是更改​​其length属性值:

const arr = [11, 22, 33, 44, 55, 66];
// truncantingarr.length = 3;console.log(arr); //=> [11, 22, 33]
// clearingarr.length = 0;console.log(arr); //=> []console.log(arr[2]); //=> undefined
2.通过对象分解模拟命名参数 (2. Simulating named parameters with object destructuring)

Chances are high that you’re already using configuration objects when you need to pass a variable set of options to some function, like this:

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

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

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:

这是一个古老但有效的模式,它试图模拟JavaScript中的命名参数。 函数调用看起来不错。 另一方面,配置对象处理逻辑不必要地冗长。 通过ES2015对象分解,您可以避免以下缺点:

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

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

而且,如果您需要使config对象成为可选对象,那么它也非常简单:

function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 } = {}) {  // ...}
3.数组项的对象分解 (3. 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.切换范围 (4. Switch with ranges)

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.

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

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:

这是在switch语句中使用范围的简单技巧:

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.使用async / await等待多个异步功能 (5. Await multiple async functions with async/await)

It’s possible to await multiple async functions to finish by using Promise.all:

使用Promise.all可以await多个异步功能完成:

await Promise.all([anAsyncCall(), thisIsAlsoAsync(), oneMore()])
6.创建纯净的对象 (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任何属性或方法(例如, constructortoString()等)。

const pureObject = Object.create(null);
console.log(pureObject); //=> {}console.log(pureObject.constructor); //=> undefinedconsole.log(pureObject.toString); //=> undefinedconsole.log(pureObject.hasOwnProperty); //=> undefined
7.格式化JSON代码 (7. Formatting JSON code)

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.从数组中删除重复项 (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集和Spread运算符,可以轻松地从数组中删除重复项:

const removeDuplicateItems = arr => [...new Set(arr)];
removeDuplicateItems([42, 'foo', 42, 'foo', true, true]);//=> [42, "foo", true]
9.展平多维数组 (9. Flattening multidimensional arrays)

Flattening arrays is trivial with Spread operator:

使用Spread运算符可以使数组变平整:

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。

翻译自: https://www.freecodecamp.org/news/9-neat-javascript-tricks-e2742f2735c3/

精巧笔驱动

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值