10个实用的JavaScript代码简写技巧与最佳实践

作者:代码拾荒

时间:2026-10-26

浏览:292

本文总结了10种常用的JavaScript代码简写技巧,涵盖数组合并、克隆、解构赋值、模板字面量、循环遍历及短路求值等场景。通过对比普通写法与ES6简写方式,展示如何减少代码行数并提高可读性。同时补充了箭头函数、对象查找等进阶用法,并强调遵循代码规范对团队协作、Bug减少及维护成本降低的重要性。

文章目录

1. 合并数组

常规实现方式如下:

我们通常使用Array中的concat()方法合并两个数组。用concat()方法来合并两个或多个数组,不会更改现有的数组,而是返回一个新的数组。请

一个简单的示例如下:

let apples = ['🍎', '🍏'];
let fruits = ['🍉', '🍊', '🍇'].concat(apples);
console.log( fruits );
//=> ["🍉", "🍊", "🍇", "🍎", "🍏"]

简写实现方式:

利用ES6的扩展运算符(...)可以简化代码,示例如下:

let apples = ['🍎', '🍏'];
let fruits = ['🍉', '🍊', '🍇', ...apples];  // <-- here
console.log( fruits );
//=> ["🍉", "🍊", "🍇", "🍎", "🍏"]

2. 在数组开头合并

常规实现方式:假设我们需要将apples数组的所有元素添加到Fruits数组的开头,而非末尾。可以使用Array.prototype.unshift()来实现:

let apples = ['🍎', '🍏'];
let fruits = ['🥭', '🍌', '🍒'];
// Add all items from apples onto fruits at start
Array.prototype.unshift.apply(fruits, apples)
console.log( fruits );
//=> ["🍎", "🍏", "🥭", "🍌", "🍒"]

简写实现方式:

同样可以使用ES6扩展运算符(...)来简化这段代码,如下所示:

let apples = ['🍎', '🍏'];
let fruits = [...apples, '🥭', '🍌', '🍒'];  // <-- here
console.log( fruits );
//=> ["🍎", "🍏", "🥭", "🍌", "🍒"]

3. 克隆数组

常规实现方式:

我们可以利用Array.slice()方法轻松完成数组克隆,示例如下:

let fruits = ['🍉', '🍊', '🍇', '🍎'];
let cloneFruits = fruits.slice();
console.log( cloneFruits );
//=> ["🍉", "🍊", "🍇", "🍎"]

简写实现方式:

使用ES6扩展运算符(...)即可实现数组克隆,代码如下:

let fruits = ['🍉', '🍊', '🍇', '🍎'];
let cloneFruits = [...fruits];  // <-- here
console.log( cloneFruits );
//=> ["🍉", "🍊", "🍇", "🍎"]

4. 解构赋值

常规实现方式:

在处理数组时,有时需要将数组元素“解包”为多个变量,示例如下:

let apples = ['🍎', '🍏'];
let redApple = apples[0];
let greenApple = apples[1];
console.log( redApple );    //=> 🍎
console.log( greenApple );  //=> 🍏

简写实现方式:

通过解构赋值,可以用一行代码实现相同效果:

let apples = ['🍎', '🍏'];
let [redApple, greenApple] = apples;  // <-- here
console.log( redApple );    //=> 🍎
console.log( greenApple );  //=> 🍏

5. 模板字面量

常规实现方式:

通常,当我们需要在字符串中嵌入表达式时,会采用以下方式:

// Display name in between two strings
let name = 'Palash';
console.log('Hello, ' + name + '!');
//=> Hello, Palash!
// Add & Subtract two numbers
let num1 = 20;
let num2 = 10;
console.log('Sum = ' + (num1 + num2) + ' and Subtract = ' + (num1 - num2));
//=> Sum = 30 and Subtract = 10

简写实现方式:

利用模板字面量,可以使用反引号((``),这样我们就可以将表达式包装在)将表达式包装在${…}中并嵌入字符串,示例如下:

// Display name in between two strings
let name = 'Palash';
console.log(`Hello, ${name}!`);  // <-- No need to use + var + anymore
//=> Hello, Palash!
// Add two numbers
let num1 = 20;
let num2 = 10;
console.log(`Sum = ${num1 + num2} and Subtract = ${num1 - num2}`);
//=> Sum = 30 and Subtract = 10

6. For循环

常规实现方式:

我们可以使用for循环来遍历数组,示例如下:

let fruits = ['🍉', '🍊', '🍇', '🍎'];
// Loop through each fruit
for (let index = 0; index < fruits.length; index++) { 
  console.log( fruits[index] );  // <-- get the fruit at current index
}
//=> 🍉
//=> 🍊
//=> 🍇
//=> 🍎

简写实现方式:

使用for...of语句可以实现相同效果,且代码量更少,示例如下:

let fruits = ['🍉', '🍊', '🍇', '🍎'];
// Using for...of statement 
for (let fruit of fruits) {
  console.log( fruit );
}
//=> 🍉
//=> 🍊
//=> 🍇
//=> 🍎

7. 箭头函数

常规实现方式:

遍历数组时,还可以使用Array.forEach()方法。虽然比最常见的for循环代码少,但仍比for...of语句多:

let fruits = ['🍉', '🍊', '🍇', '🍎'];
// Using forEach method
fruits.forEach(function(fruit){
  console.log( fruit );
});
//=> 🍉
//=> 🍊
//=> 🍇
//=> 🍎

简写实现方式:

使用箭头函数表达式,可以用一行代码编写完整的循环逻辑,示例如下:

let fruits = ['🍉', '🍊', '🍇', '🍎'];
fruits.forEach(fruit => console.log( fruit ));  // <-- Magic ✨
//=> 🍉
//=> 🍊
//=> 🍇
//=> 🍎

8. 在数组中查找对象

常规实现方式:

若需通过属性从对象数组中查找对象,通常使用for循环:

let inventory = [
  {name: 'Bananas', quantity: 5},
  {name: 'Apples', quantity: 10},
  {name: 'Grapes', quantity: 2}
];
// Get the object with the name `Apples` inside the array
function getApples(arr, value) {
  for (let index = 0; index < arr.length; index++) {
    // Check the value of this object property `name` is same as 'Apples'
    if (arr[index].name === 'Apples') {  //=> 🍎

      // A match was found, return this object
      return arr[index];
    }
  }
}
let result = getApples(inventory);
console.log( result )
//=> { name: "Apples", quantity: 10 }

简写实现方式:

上述逻辑若使用Array.find()方法配合箭头函数(=>),可简化为一行代码:

// Get the object with the name `Apples` inside the array
function getApples(arr, value) {
  return arr.find(obj => obj.name === 'Apples');  // <-- here
}
let result = getApples(inventory);
console.log( result )
//=> { name: "Apples", quantity: 10 }

9. 将字符串转换为整数

常规实现方式:

使用parseInt()函数解析字符串并返回整数:

let num = parseInt("10")
console.log( num )         //=> 10
console.log( typeof num )  //=> "number"

简写实现方式:

在字符串前添加+前缀即可实现相同效果,示例如下:

let num = +"10";
console.log( num )           //=> 10
console.log( typeof num )    //=> "number"
console.log( +"10" === 10 )  //=> true

10. 短路求值

常规实现方式:

若需根据另一个非falsy值设置变量,通常使用if-else语句,示例如下:

function getUserRole(role) {
  let userRole;
  // If role is not falsy value
  // set `userRole` as passed `role` value
  if (role) {
    userRole = role;
  } else {
    // else set the `userRole` as USER
    userRole = 'USER';
  }
  return userRole;
}
console.log( getUserRole() )         //=> "USER"
console.log( getUserRole('ADMIN') )  //=> "ADMIN"

简写实现方式:

利用短路求值(||),可以用一行代码完成操作,示例如下:

function getUserRole(role) {
  return role || 'USER';  // <-- here
}
console.log( getUserRole() )         //=> "USER"
console.log( getUserRole('ADMIN') )  //=> "ADMIN"

补充几点

箭头函数:

若无需this上下文,使用箭头函数可使代码更简洁:

let fruits = ['🍉', '🍊', '🍇', '🍎'];
fruits.forEach(console.log);

在数组中查找对象:

结合对象解构与箭头函数,可使代码更精简:

// Get the object with the name `Apples` inside the array
const getApples = array => array.find(({ name }) => name === "Apples");
let result = getApples(inventory);
console.log(result);
//=> { name: "Apples", quantity: 10 }

短路求值替代方案:

const getUserRole1 = (role = "USER") => role;
const getUserRole2 = role => role ?? "USER";
const getUserRole3 = role => role ? role : "USER";

编码习惯

最后谈谈编码习惯。尽管代码规范众多,但很少有人严格遵守。主要原因在于制定规范前,开发者已形成个人习惯,难以短期改变。良好的编码习惯有助于后续成长。以下列举开发规范的几点好处,以说明其重要性:

  • 规范的代码可促进团队合作。
  • 规范的代码可减少Bug处理。
  • 规范的代码可降低维护成本。
  • 规范的代码有助于代码审查。
  • 养成代码规范习惯,有助于程序员自身成长。

到此这篇关于总结分享10 个超棒的 JavaScript 简写技巧的文章就介绍到这了,更多相关JS简写技巧内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章