18个JavaScript编写简洁高效代码的技巧分享

作者:小括号

时间:2026-10-31

浏览:634

本文精选18个JavaScript实用技巧,涵盖箭头函数、Array.from、解构赋值、Map、Object.seal/freeze等核心语法。通过具体示例展示如何简化声明、处理数组与对象、优化性能及提升代码可读性,帮助开发者写出更简洁高效的JS代码。

文章目录

本文内容基于《18 JavaScript Tips: You Should Know for Clean and Efficient Code》翻译整理,作者Shefali,部分细节已做删改。

箭头函数

利用箭头函数可以简化函数的定义过程。

function add(a, b) {
  return a + b;
}

// Arrow function
const add = (a, b) => a + b;

Array.from()

利用Array.from()方法,能够将任意可迭代对象转换为数组。

const str = "Hello!";
const arr = Array.from(str);

console.log(arr); //Output: ['H', 'e', 'l', 'l', 'o', '!']

使用console.table显示数据

若需在控制台以表格形式组织并展示数据,可调用console.table()。

const person = {
    name: 'John', 
    age: 25,
    profession: 'Programmer'
}
console.table(person);

输出效果:

箭头函数

使用const和let

对于确定不会重新赋值的变量,推荐使用const。

const PI = 3.14;
let timer = 0;

使用解构提取对象属性

通过解构语法从对象中提取属性,有助于提升代码的可读性。

const person = {
    name: 'John', 
    age: 25,
    profession: 'Programmer'
}

//Instead of this 👇
console.log(person.name);
console.log(person.age);

//Use this👇
const {name, age} = person;
console.log(name);
console.log(age);

使用逻辑OR运算符设置默认值

借助||操作符可以便捷地设置默认值。

function greet(name) {
  name = name || 'Person';
  console.log(`Hello, ${name}!`);
}

greet(); //Output: Hello, Person!
greet("John"); //Output: Hello, John!

清空数组

通过设置length属性为0,可以简便地清空数组。

let numbers = [1, 2, 3, 4];
numbers.length = 0;
console.log(numbers); //Output: []

JSON.parse()

调用JSON.parse()可将JSON字符串解析为JavaScript对象,确保数据操作的流畅性。

const jsonStr = '{"name": "John", "age": 25}';
const person = JSON.parse(jsonStr);
console.log(person); 
//Output: {name: 'John', age: 25}

Map()函数

利用map()函数可转换新数组中的元素,且不会修改原始数组。

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(numbers); //Output: [1, 2, 3, 4]
console.log(doubled); //Output: [2, 4, 6, 8]

Object.seal()

通过Object.seal()方法,可以防止向对象中添加或删除属性。

const person = {
    name: 'John', 
    age: 25
};
Object.seal(person);
person.profession = "Programmer";
console.log(person); //Output: {name: 'John', age: 25}

Object.freeze()

利用Object.freeze()方法,可阻止对对象进行任何更改,包括添加、修改或删除属性。

const person = {
    name: 'John', 
    age: 25
};
Object.freeze(person);
person.name = "Mark";
console.log(person); //Output: {name: 'John', age: 25}

删除数组重复项

借助Set可以从数组中移除重复元素。

const arrWithDuplicates = [1, 12, 2, 13, 4, 4, 13];
const arrWithoutDuplicates = [...new Set(arrWithDuplicates)];
console.log(arrWithoutDuplicates); 
//Output: [1, 12, 2, 13, 4]

使用解构交换值

利用解构语法可以轻松地交换两个变量的值。

let x = 7, y = 13;
[x, y] = [y, x];
console.log(x); //13

扩展运算符

使用扩展运算符可以高效地复制或合并数组。

const arr1 = [1, 2, 3];
const arr2 = [9, 8, 7];

const arr3 = [...arr2];
const mergedArr = [...arr1, ...arr2];

console.log(arr3); //[9, 8, 7]
console.log(mergedArr); //[1, 2, 3, 9, 8, 7]

模板字符串

利用模板字符串进行插值操作,能增强代码的可读性。

const name = 'John';
const message = `Hello, ${name}!`;

三元运算符

使用三元运算符可以简化条件语句的书写。

const age = 20;

//Instead of this👇
if(age>=18){
    console.log("You can drive");
}else{
    console.log("You cannot drive");
}

//Use this👇
age >= 18 ? console.log("You can drive") : console.log("You cannot drive");

使用===代替==

通过严格相等(===)替代==,可避免类型强制转换带来的问题。

const num1 = 5;
const num2 = '5';

//Instead of using ==
if (num1 == num2) {
  console.log('True');
} else {
  console.log('False');
}

//Use ===
if (num1 === num2) {
  console.log('True');
} else {
  console.log('False');
}

使用语义化变量和函数名称

为变量和函数赋予有意义且描述性的名称,有助于提升代码的可读性和可维护性。

// Don't declare variable like this
const a = 18;

// use descriptive names
const numberOfTips = 18;

以上即为18个JavaScript编写简洁高效代码的技巧分享,更多关于JavaScript技巧的资料请关注本站其它相关文章!

实用工具推荐

电子包浆

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

使用 ›
图片压缩

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

使用 ›
相关文章