常用的JavaScript简写技巧

分类:技术最近更新:2026-04-15浏览:1352

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

1、声明变量

javascript
//Longhand let x; let y = 20; //Shorthand let x, y = 20;

2、给多个变量赋值

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

javascript
//Longhand let a, b, c; a = 5; b = 8; c = 12; //Shorthand let [a, b, c] = [5, 8, 12];

3、三元运算符

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

javascript
//Longhand let marks = 26; let result; if(marks >= 30){ result = 'Pass'; }else{ result = 'Fail'; } //Shorthand let result = marks >= 30 ? 'Pass' : 'Fail';

4、赋默认值

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

javascript
//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 时调用一个函数,那么你可以使用与 (&&)短路形式书写。

javascript
//Longhand if (isLoggedin) { goToHomepage(); } //Shorthand isLoggedin && goToHomepage();

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

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

6、交换两个变量

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

javascript
let x = 'Hello', y = 55; //Longhand const temp = x; x = y; y = temp; //Shorthand [x, y] = [y, x];

7、箭头函数

javascript
//Longhand function add(num1, num2) { return num1 + num2; } //Shorthand const add = (num1, num2) => num1 + num2;

8、模板字符串

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

javascript
//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)。我们可以使用 (`) 以一种更简单的方式实现。

javascript
//Longhand console.log('JavaScript, often abbreviated as JS, is a\n' + 'programming language that conforms to the \n' + 'ECMAScript specification. JavaScript is high-level,\n' + 'often just-in-time compiled, and multi-paradigm.' ); //Shorthand 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.`);

10、多条件检查

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

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

11、对象属性复制

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

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

12、字符串转成数字

有一些内置的方法,例如parseInt和parseFloat可以用来将字符串转为数字。我们还可以简单地在字符串前提供一个一元运算符 (+) 来实现这一点。

javascript
//Longhand let total = parseInt('453'); let average = parseFloat('42.6'); //Shorthand let total = +'453'; let average = +'42.6';

13、重复一个字符串多次

为了重复一个字符串 N 次,你可以使用for循环。但是使用repeat()方法,我们可以一行代码就搞定。

javascript
//Longhand let str = ''; for(let i = 0; i < 5; i++) { str += 'Hello '; } //Shorthand let str = 'Hello '.repeat(5);

14、深拷贝对象

javascript
//Longhand function makeDeepClone(obj) { let newObject = {}; Object.keys(obj).map(key => { if(typeof obj[key] === 'object'){ newObject[key] = makeDeepClone(obj[key]); } else { newObject[key] = obj[key]; } }); return newObject; } const cloneObj = makeDeepClone(obj); //Shorthand const cloneObj = JSON.parse(JSON.stringify(obj)); //Shorthand for single level object let obj = {x: 20, y: 'hello'}; const cloneObj = {...obj};

15、获取字符串中的字符

javascript
let str = 'jscurious.com'; //Longhand str.charAt(2); // c //Shorthand str[2]; // c