JavaScript 高效编码:20 个常用简写技巧与最佳实践

作者:异步漫步时间:2026-10-22 07:22:33浏览:422

本文整理了 JavaScript 开发中常用的 20 种简写技巧,涵盖三元运算符、短路求值、箭头函数、解构赋值及 ES6 新增特性。通过对比传统写法与简写方式,帮助开发者提升代码可读性与执行效率,适用于现代前端开发场景。

JavaScript 简写技巧概述

JavaScript 作为网络脚本语言,广泛应用于网页设计优化、表单验证、浏览器检测及 Cookie 创建等场景。因其易用性,越来越多的开发者倾向于使用 JavaScript 实现功能。为满足高效开发与代码规范的要求,掌握常用的 JavaScript 简写技巧至关重要。以下内容整理了实用的简写方法,供开发者参考。

基础语法简写:三元运算符与变量声明

1. 三元运算符

当需要使用单行代码替代 if...else 语句时,三元运算符是理想选择。例如:


const x = 20;
let answer;
if (x > 10) {
 answer = 'is greater';
} else {
 answer = 'is lesser';
}

可简写为:

const answer = x > 10 ? 'is greater' : 'is lesser';

此外,三元运算符支持嵌套 if 语句:

const big = x > 10 ? " greater 10" : x

逻辑与条件判断简写

2. 简写短路求值

在将变量赋值给另一个值时,若需确保初始值不为 null、undefined 或空字符串,可编写多重条件的 if 语句:


if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
  let variable2 = variable1;
}

或者利用短路求值方法:

const variable2 = variable1 || 'new';

3. 简写变量声明

定义函数时,若需声明多个变量,例如:


let x;
let y;
let z = 3;

可使用简写方式同时声明多个变量,以节省时间与空间:

let x, y, z=3;

4. 简写 if 执行条件

在进行 if 条件检查时,若赋值操作可省略,例如:

if (likeJavaScript === true)

可简写为:

if (likeJavaScript)

仅当 likeJavaScript 为真值时,上述两种写法可互换。若判断假值,例如:


let a;
if ( a !== true ) {
 // do something...
}

可简写为:


let a;
if ( !a ) {
 // do something...
}

循环与数组操作简写

5. 简写 JavaScript 循环方法

在纯 JavaScript 开发中,若不依赖 jQuery 等外部库,此方法非常实用。

for (let i = 0; i < allImgs.length; i++)

可简写为:

for (let index in allImgs)

也可使用 Array.forEach:


function logArrayElements(element, index, array) {
 console.log("a[" + index + "] = " + element);
}
[2, 5, 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[2] = 9

6. 短路求值

若需通过判断参数是否为 null 或 undefined 来分配默认值,无需编写多行代码,可使用短路逻辑运算符,仅用一行代码完成相同操作。例如:


let dbHost;
if (process.env.DB_HOST) {
 dbHost = process.env.DB_HOST;
} else {
 dbHost = 'localhost';
}

可简写为:

const dbHost = process.env.DB_HOST || 'localhost';

7. 十进制指数

当数字尾部包含大量零(如 10000000)时,可使用指数形式(1e7)替代。例如:

for (let i = 0; i < 10000; i++) {}

可简写为:

for (let i = 0; i < 1e7; i++) {}


// 下面都是返回 true
1e0 === 1;
1e1 === 10;
1e2 === 100;
1e3 === 1000;
1e4 === 10000;
1e5 === 100000;

ES6 对象与函数特性

8. 简写对象属性

在 JavaScript 中定义对象很简单,ES6 提供了更简便的对象属性分配方法。若属性名与 key 值相同,例如:

const obj = { x:x, y:y };

则可简写为:

const obj = { x, y };

9. 简写箭头函数

传统函数易于理解与编写,但在嵌套于其他函数时可能显得冗长混乱。例如:


function sayHello(name) {
 console.log('Hello', name);
}

setTimeout(function() {
 console.log('Loaded')
}, 2000);

list.forEach(function(item) {
 console.log(item);
});

此时,可简写为:

sayHello = name => console.log('Hello', name);

setTimeout(() => console.log('Loaded'), 2000);

list.forEach(item => console.log(item));

10. 简写隐式返回值

常使用 return 语句返回函数最终结果。仅有一行声明的箭头函数可隐式返回值(此时需省略 {} 以省略 return 关键字)。若需返回多行语句,则需用 () 包围函数体。例如:


function calcCircumference(diameter) {
 return Math.PI * diameter
}
var func = function func() {
 return { foo: 1 };
};

可简写为:


calcCircumference = diameter => (
 Math.PI * diameter;
)
var func = () => ({ foo: 1 });

11. 默认参数值

常使用 if 语句为函数参数定义默认值。但在 ES6 中,可在函数声明中直接指定默认值。例如:


function volume(l, w, h) {
 if (w === undefined)
  w = 3;
 if (h === undefined)
  h = 4;
 return l * w * h;
}

可简写为:

volume = (l, w = 3, h = 4 ) => (l * w * h);

volume(2) // output: 24

字符串与解构赋值技巧

12. 字符串模板

若厌倦使用 + 将多个变量转换为字符串,且使用 ES6,则只需使用反引号并将变量置于 ${} 中即可。例如:


const welcome = 'You have logged in as ' + first + ' ' + last + '.'

const db = 'http://' + host + ':' + port + '/' + database;

可简写为:


const welcome = `You have logged in as ${first} ${last}`;

const db = `http://${host}:${port}/${database}`;

13. 简写赋值方法

在使用流行 Web 框架时,常通过数组或对象在组件与 API 间通信。数据到达组件后需解构。例如:


const observable = require('mobx/observable');
const action = require('mobx/action');
const runInAction = require('mobx/runInAction');

const store = this.props.store;
const form = this.props.form;
const loading = this.props.loading;
const errors = this.props.errors;
const entity = this.props.entity;

可简写为:


import { observable, action, runInAction } from 'mobx';

const { store, form, loading, errors, entity } = this.props;

也可分配变量名:

// 最后一个变量名为 contact

const { store, form, loading, errors, entity:contact } = this.props;

14. 简写多行字符串

若需在代码中编写多行字符串,通常使用 + 拼接。例如:


const lorem = 'Lorem ipsum dolor sit amet, consectetur\n\t'
 + 'adipisicing elit, sed do eiusmod tempor incididunt\n\t'
 + 'ut labore et dolore magna aliqua. Ut enim ad minim\n\t'
 + 'veniam, quis nostrud exercitation ullamco laboris\n\t'
 + 'nisi ut aliquip ex ea commodo consequat. Duis aute\n\t'
 + 'irure dolor in reprehenderit in voluptate velit esse.\n\t'

若使用反引号,即可达到简写目的:


const lorem = `Lorem ipsum dolor sit amet, consectetur
 adipisicing elit, sed do eiusmod tempor incididunt
 ut labore et dolore magna aliqua. Ut enim ad minim
 veniam, quis nostrud exercitation ullamco laboris
 nisi ut aliquip ex ea commodo consequat. Duis aute
 irure dolor in reprehenderit in voluptate velit esse.`

扩展运算符与参数处理

15. 扩展运算符

ES6 中的扩展运算符可使操作更简单。例如:


// joining arrays
const odd = [1, 3, 5];
const nums = [2 ,4 , 6].concat(odd);

// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = arr.slice()

可简写为:


// joining arrays
const odd = [1, 3, 5];
const nums = [2 ,4 , 6, ...odd];
console.log(nums); // [2, 4, 6, 1, 3, 5]

// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = [...arr];

与 concat() 函数不同,扩展运算符可在数组任意位置插入另一个数组。例如:


const odd = [1, 3, 5 ];
const nums = [2, ...odd, 4, 6];

也可使用扩展运算符:


const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4 };
console.log(a) // 1
console.log(b) // 2
console.log(z) // { c: 3, d: 4 }

16. 强制参数

默认情况下,若未传递值,JavaScript 会将函数参数设为 undefined,而其他语言可能报错。为实现参数分配,可让 if 语句抛出 undefined 错误,或使用“强制参数”方法。例如:


function foo(bar) {
 if(bar === undefined) {
  throw new Error('Missing parameter!');
 }
 return bar;
}

可简写为:


mandatory = () => {
 throw new Error('Missing parameter!');
}

foo = (bar = mandatory()) => {
 return bar;
}

高级数组与对象操作

17. Array.find 简写

若曾负责编写 JavaScript 中的 find 函数,可能使用了 for 循环。此处介绍 ES6 中的 Array.find() 方法。


const pets = [
 { type: 'Dog', name: 'Max'},
 { type: 'Cat', name: 'Karl'},
 { type: 'Dog', name: 'Tommy'},
]

function findDog(name) {
 for(let i = 0; i<pets.length; ++i) {
 if(pets[i].type === 'Dog' && pets[i].name === name) {
  return pets[i];
 }
 }
}

可简写为:


pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy');
console.log(pet); // { type: 'Dog', name: 'Tommy' }

18. 简写 Object[key]

Foo.bar 也可写成 Foo['bar']。起初看似无必要,但此符号为编写可重用代码提供了基础。考虑如下简化验证函数示例:


function validate(values) {
 if(!values.first)
 return false;
 if(!values.last)
 return false;
 return true;
}
console.log(validate({first:'Bruce',last:'Wayne'})); // true

该函数可完美完成任务。但若需验证多个表单,且字段与规则不同,构建可在运行时配置的通用验证函数将更为便捷。


// 对象验证规则
const schema = {
 first: {
 required:true
 },
 last: {
 required:true
 }
}

// 通用验证函数
const validate = (schema, values) => {
 for(field in schema) {
 if(schema[field].required) {
  if(!values[field]) {
  return false;
  }
 }
 }
 return true;
}
console.log(validate(schema, {first:'Bruce'})); // false
console.log(validate(schema, {first:'Bruce',last:'Wayne'})); // true

现在即可拥有可在所有表单中重用的验证函数,无需为每个表单编写自定义验证函数。

按位运算符与总结

19. 简写双重按位非运算符

按位运算符在初学 JavaScript 时了解,但常无使用场景。若不处理二进制,谁又会操作 0 和 1?然而,双重按位非运算符非常实用,例如可替代 floor() 函数,且与其他相同操作相比,按位运算符速度更快。

Math.floor(4.9) === 4 //true

可简写为:

~~4.9 === 4 //true

20. Suggest One of U?

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助~如果有疑问大家可以留言交流,谢谢大家对本站的支持!

作者最新文章