14

20 个常用的 JavaScript 简写技巧

 3 years ago
source link: https://www.infoq.cn/article/bVel6CuZ0EmfGxwsq3dg
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

任何编程语言的简写技巧都能够帮助你编写更简练的代码,让你用更少的代码实现你的目标。让我们一个个来看看 JavaScript 的简写技巧吧。

1. 声明变量

//Longhand let x; let y = 20; 

//Shorthand let x, y = 20;

复制代码

2. 给多个变量赋值

我们可以使用数组解构来在一行中给多个变量赋值。

<code data-type="codeline">//Longhand </code><code data-type="codeline">let a, b, c; </code><code data-type="codeline">a = 5; </code><code data-type="codeline">b = 8; </code><code data-type="codeline">c = 12;</code><code data-type="codeline"> </code><code data-type="codeline">//Shorthand </code><code data-type="codeline">let [a, b, c] = [5, 8, 12];</code>

复制代码

3. 三元运算符

我们可以使用三元(条件)运算符在这里节省 5 行代码。

<code data-type="codeline">//Longhand </code><code data-type="codeline">let marks = 26; </code><code data-type="codeline">let result; </code><code data-type="codeline">if(marks >= 30){</code><code data-type="codeline"> result = 'Pass'; </code><code data-type="codeline">}else{ </code><code data-type="codeline"> result = 'Fail'; </code><code data-type="codeline">} </code><code data-type="codeline">//Shorthand </code><code data-type="codeline">let result = marks >= 30 ? 'Pass' : 'Fail';</code>

复制代码

4. 赋默认值

我们可以使用 OR(||)短路运算来给一个变量赋默认值,如果预期值不正确的情况下。

//Longhand let imagePath; let path = getImagePath(); if(path !== null && path !== undefined && path !== '') {   imagePath = path; } else {   imagePath = 'default.jpg'; } 

//Shorthand let imagePath = getImagePath() || 'default.jpg';

复制代码

5. 与(&&) 短路运算

如果你只有当某个变量为 true 时调用一个函数,那么你可以使用 与(&&) 短路形式书写。

//Longhand if (isLoggedin) { goToHomepage(); } 

//Shorthand isLoggedin && goToHomepage();

复制代码

当你在 React 中想要有条件地渲染某个组件时,这个 与(&&) 短路写法比较有用。例如:

<div> { this.state.isLoading && <Loading /> } </div>

复制代码

6. 交换两个变量

为了交换两个变量,我们通常使用第三个变量。我们可以使用数组解构赋值来交换两个变量。

let x = 'Hello', y = 55; //Longhand const temp = x; x = y; y = temp; 

//Shorthand [x, y] = [y, x];

复制代码

7. 箭头函数

//Longhand function add(num1, num2) {    return num1 + num2; } 

//Shorthand const add = (num1, num2) => num1 + num2;

复制代码

参考: JavaScript Arrow function

8. 模板字符串

我们一般使用+运算符来连接字符串变量。使用 ES6 的模板字符串,我们可以用一种更简单的方法实现这一点。

//Longhand console.log('You got a missed call from ' + number + ' at ' + time); 

//Shorthand console.log(`You got a missed call from ${number} at ${time}`);

复制代码

9. 多行字符串

对于多行字符串,我们一般使用+运算符以及一个新行转义字符(\n)。我们可以使用(`)以一种更简单的方式实现。

<code data-type="codeline">//Longhand </code><code data-type="codeline">console.log('JavaScript, often abbreviated as JS, is a\n' +             'programming language that conforms to the \n' + </code><code data-type="codeline">'ECMAScript specification. JavaScript is high-level,\n' + </code><code data-type="codeline">'often just-in-time compiled, and multi-paradigm.' ); </code><code data-type="codeline">//Shorthand </code><code data-type="codeline">console.log(`JavaScript, often abbreviated as JS, is a programming language that conforms to the ECMAScript specification. JavaScript is high-level, often just-in-time compiled, and multi-paradigm.`);</code>

复制代码

10. 多条件检查

对于多个值匹配,我们可以将所有的值放到数组中,然后使用 indexOf()includes() 方法。

//Longhand if (value === 1 || value === 'one' || value === 2 || value === 'two') {      // Execute some code } 

// Shorthand 1if ([1, 'one', 2, 'two'].indexOf(value) >= 0) { // Execute some code }// Shorthand 2if ([1, 'one', 2, 'two'].includes(value)) { // Execute some code }

复制代码

11. 对象属性复制

如果变量名和对象的属性名相同,那么我们只需要在对象语句中声明变量名,而不是同时声明键和值。JavaScript 会自动将键作为变量的名,将值作为变量的值。

let firstname = 'Amitav'; let lastname = 'Mishra'; //Longhand let obj = {firstname: firstname, lastname: lastname}; 

//Shorthand let obj = {firstname, lastname};

复制代码

12. 字符串转成数字


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK