编写javascript_编写javascript和打字稿时的一些最佳快捷方式

编写javascript

Everyone knows that Javascript and Typescript have several weird and hidden features that allow you to shorten the amount of code you write. To preface this article, I’d like to impose upon you an important tidbit of information, short and efficient code doesn’t always equal good code. As always, you should be prioritizing readability over implementing a bunch of fancy features.

每个人都知道Javascript和Typescript具有一些怪异和隐藏的功能,可让您缩短编写的代码量。 在开始本文之前,我想向您介绍一些重要的信息, 短而有效的代码并不总是等同于好的代码。 与往常一样,您应该优先考虑可读性,而不要实现一系列精美的功能。

That being said, these features can help you save tons of space and used properly are easily understandable to anyone else who’s reading your code. Let’s go over some of these shorthand features so that you can use and understand them in your code.

话虽如此,这些功能可以帮助您节省大量空间,并且其他正在阅读您的代码的人都容易理解正确使用这些功能。 让我们看一下其中的一些速记功能,以便您可以在代码中使用和理解它们。

1.三元运算符 (1. The Ternary Operator)

This is probably the most well-known shorthand Javascript function, the shortened “if-else” statement. By using this operator, you can remove a lot of the if else boilerplate and turn four lines into one!

这可能是最著名的速记Javascript函数,即缩短的“ if-else”语句。 通过使用此运算符,您可以删除很多if else样板并将四行转换为一行!

let v = true;
// Traditional approach
if (v) {
console.log('True');
} else {
console.log('False');
}
// Ternary Operator
v ? console.log('True') : console.log('False');

The structure is as follows: <conditional expression> ? <true case> : <false case?. Pretty simple, right? This is a great way to do one line if else operations and is especially useful when combined with other shorthand operators.

结构如下: <conditional expression> ? <true case> : <false case? <conditional expression> ? <true case> : <false case? 。 很简单,对吧? 这是执行单行操作的好方法,并且在与其他速记运算符结合使用时特别有用。

2. Typescript的构造方法速记 (2. Typescript’s Constructor Shorthand)

This one is particularly for Typescript (Sorry vanilla JS users), but is a great feature when building classes.

这个特别适合Typescript(对不起vanilla JS用户),但是在构建类时是一个很棒的功能。

Normally in a class, you have to list all your class variables then reassign them in your constructor, which takes tons of lines of code. But if your class is relatively simple (you’re just assigning parameters to private variables), Typescript has a great way to cut the amount of code you write.

通常,在一个类中,您必须列出所有类变量,然后在构造函数中重新分配它们,这需要大量的代码行。 但是,如果您的类相对简单(您只是将参数分配给私有变量),Typescript可以减少您编写的代码量。

// Normal way
class Location {
private _latitude: string;
private _longitude: string;
constructor(latitude: string, longitude: string) {
this._latitude = latitude;
this._longitude = longitude;
}
}
// Shorthand in TypeScript
class Location {
constructor(
private _latitude: string,
private _longitude: string
) {}
}

On larger classes with tons of properties, this can be a real lifesaver!

在具有大量属性的较大类中,这可能是真正的救星!

3.空头算子 (3. Nullish Operator)

Often misunderstood, the nullish operator lets you easily evaluate an expression and check if it’s null, and return a default value if it is null.

经常被误解的是,空值运算符使您可以轻松地计算表达式并检查它是否为空,如果它为空,则返回默认值。

function nullish(value1, value2) {
// If value1 is null returns 'default'
let v1 = value1 ?? 'default';
return v1 + value2;
}
myFn("this has no") //returns "this has no default"
myFn("this has no", 0) //returns "this has no 0"

Actually, technically it checks for null or undefined, but the name is close enough. This is a great way to check if values exist or not.

实际上,从技术上讲,它检查nullundefined ,但名称足够接近。 这是检查值是否存在的好方法。

4.对象属性分配 (4. Object Property Assignment)

ES6 simplified the process of assigning values to objects. If values are assigned to variables named exactly as the object’s properties, you won’t have to repeat the name!

ES6简化了为对象分配值的过程。 如果将值赋给与该对象的属性完全相同的变量,则无需重复该名称!

let name: string = "Caelin";
let age: number = 18;
interface User {
name: string;
age: number;
}
// Old way (manual assignment)
let user1: User = {
name: name,
age: age,
}
// New way!
let user2: User = {
name,
age,
}

As shown above, the new way is considerably simpler and DRYer than the old way!

如上所示,新方法比旧方法简单得多且更干燥!

5.箭头/ Lambda函数 (5. Arrow/Lambda Functions)

If you’ve seen a lot of these operators: => thrown around everywhere, they’re arrow functions. These allow you to save a return statement since any lamda function will have a default return.

如果您已经看到很多这样的运算符: =>到处都是,它们就是箭头函数。 这些允许您保存return语句,因为任何lamda函数都将具有默认的return。

You’ll seen them often used in array operators as such:

您会看到它们经常在数组运算符中使用,例如:

let arr = [1, 2, 3, 4, 5];
// Long way
arr.map(function (n) {
return n*2;
})
// Short way
arr.map(n => n*2);

As you can see, it makes the code considerably more readable and shorter.

如您所见,它使代码更具可读性且更短。

6 ..默认参数值 (6.. Default Parameter Values)

ES6 now allows you to specify default parameter values on functions! Before, you’d have to rely on OR’s lazy evaluation, which worked but was a suboptimal solution.

ES6现在允许您在函数上指定默认参数值! 在此之前,您必须依靠OR的惰性评估,该评估虽然有效,但不是最佳解决方案。

// Assigns 'c' a default value
function defaultParams(a, b, c="c") {
return a + b + c;
}

Fun tip, if you want to make a required parameter, do the following:

有趣的提示,如果要输入必需的参数,请执行以下操作:

const requiredParam = _ => throw new Error('Required Parameter!');
// Create a default parameter d
function defaultParamRequired(a, b, c="c", d=requiredParam()) {
// Logic
}

Now, if this function runs without passing a default parameter d in, it’ll throw an error! Pretty cool trick right?

现在,如果此函数在未传递默认参数d的情况下运行,则会抛出错误! 很酷的技巧吧?

7.解构和散布运算符 (7. Destructuring and Spread Operators)

I literally wrote a whole article on spread operators, but spread and destructing operations are great ways to take advantage of objects and arrays!

我从字面上写了一篇有关传播运算符的完整文章,但是传播和破坏运算是利用对象和数组的好方法!

解构 (Destructuring)

It’s quite common to want to access object parameters individually (to modify or read them) without accessing the original object. Normally, this would require a line for each object parameter, which can get quite long on larger objects. Object destructuring allows us to cut that into one line!

想要不访问原始对象而单独访问对象参数(以修改或读取它们)是很常见的。 通常,这将需要为每个对象参数设置一行,这在较大的对象上可能会变得很长。 对象解构使我们可以将其切成一行!

const user = {
name: 'Caelin',
age: 18,
}
// Normal method
const name = user.name;
const age = user.age;
// Destructuring method
const {name, age} = user;

This syntax is great for object parameters and import statements to reduce the number of lines when dealing with complex objects.

此语法非常适合对象参数和import语句,以减少处理复杂对象时的行数。

传播 (Spreading)

Spread operators make it easier to combine objects and arrays by expanding them.

扩展运算符使通过扩展对象和数组的组合变得更容易。

const arr1 = [1,2,3,4]
const arr2 = [5,6,7]
const finalArr = [...arr1, ...arr2] // [1,2,3,4,5,6,7]
const partialObj1 = {
name: "fernando"
}
const partialObj2 = {
age:37
}
const fullObj = { ...partialObj1, ...partialObj2 } // {name: "fernando", age: 37}

结论 (Conclusion)

These are just a few of the many Javascript and Typescript shortcuts that can save you time and make your code cleaner. Remember, this is not simply about making code more efficient or reducing lines, it’s about making code that’s cleaner and easier to read for the next developer.

这些只是许多Javascript和Typescript快捷方式中的一部分,可以节省您的时间并使代码更整洁。 请记住,这不只是使代码更高效或减少行数,还在于使代码更干净,更容易为下一个开发人员阅读。

Did I miss something? Be sure to comment it down below!

我错过了什么? 请务必在下方将其注释掉!

保持联系 (Keep in Touch)

There’s a lot of content out there, I appreciate you reading mine. I’m a young entrepreneur and I write about software development and my experience running companies. You can signup for my newsletter here

那里有很多内容,感谢您阅读我的内容。 我是一个年轻的企业家,我写有关软件开发和我经营公司的经验的文章。 您可以在这里注册我的时事通讯

Feel free to reach out and connect with me on Linkedin or Twitter.

请随时通过LinkedinTwitter与我联系。

翻译自: https://medium.com/@caelinsutch/some-of-the-best-shortcuts-when-writing-javascript-and-typescript-e5bc74e0702

编写javascript

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值