提升JavaScript开发效率的20个实用技巧
本文整理了20个提升JavaScript开发效率的实用技巧,涵盖数组初始化、排序、去重、对象合并及ES6+新特性如可选链、空值合并和展开运算符。通过精简代码行数,帮助开发者在编码竞赛或日常开发中写出更简洁高效的函数。
这些技术旨在减少代码行数并加速开发进程。
在开发过程中,我们常需编写排序、搜索、查找唯一值、参数传递及值交换等函数。本文汇总了部分实用技术资源,助您写出如专家般简洁的函数代码。

以下方法预计将对您的工作产生积极影响。
- 降低代码行数(LOC)
- 编码竞赛
- 黑客马拉松
- 或其他限时编程任务
这些JavaScript技巧大多基于ECMAScript6(即ES2015)之后的语法标准,尽管目前最新版本已更新至ECMAScript11(ES2020)。
请注意:下文所有技巧均在Google浏览器控制台中测试通过。
1. 数组的声明与初始化
可以使用默认值(如空字符串、null或0)来初始化特定大小的数组。您可能熟悉一维数组的初始化,但如何初始化二维数组或矩阵呢?
const array = Array(5).fill('');
// Output
(5) ["", "", "", "", ""]
const matrix = Array(5).fill(0).map(()=>Array(5).fill(0));
// Output
(5) [Array(5), Array(5), Array(5), Array(5), Array(5)]
0: (5) [0, 0, 0, 0, 0]
1: (5) [0, 0, 0, 0, 0]
2: (5) [0, 0, 0, 0, 0]
3: (5) [0, 0, 0, 0, 0]
4: (5) [0, 0, 0, 0, 0]
length: 5
2. 执行求和、求最小值与最大值运算
利用reduce方法可快速完成基础数学运算。
const array = [5,4,7,8,9,2];
求和示例
array.reduce((a,b) => a+b);
// Output: 35
最大值示例
array.reduce((a,b) => a>b?a:b);
// Output: 9
最小值示例
array.reduce((a,b) => a<b?a:b);
// Output: 2
3. 对字符串、数字或对象数组进行排序
虽然内置的sort()和reverse()方法可用于字符串排序,但数字或对象数组该如何处理?以下技巧展示了如何按递增或递减顺序对数字和对象进行排序。
字符串排序示例
const stringArr = ["Joe", "Kapil", "Steve", "Musk"]
stringArr.sort();
// Output
(4) ["Joe", "Kapil", "Musk", "Steve"]
stringArr.reverse();
// Output
(4) ["Steve", "Musk", "Kapil", "Joe"]
数字排序示例
const array = [40, 100, 1, 5, 25, 10];
array.sort((a,b) => a-b);
// Output
(6) [1, 5, 10, 25, 40, 100]
array.sort((a,b) => b-a);
// Output
(6) [100, 40, 25, 10, 5, 1]
对象排序示例
const objectArr = [
{ first_name: 'Lazslo', last_name: 'Jamf' },
{ first_name: 'Pig', last_name: 'Bodine' },
{ first_name: 'Pirate', last_name: 'Prentice' }
];
objectArr.sort((a, b) => a.last_name.localeCompare(b.last_name));
// Output
(3) [{…}, {…}, {…}]
0: {first_name: "Pig", last_name: "Bodine"}
1: {first_name: "Lazslo", last_name: "Jamf"}
2: {first_name: "Pirate", last_name: "Prentice"}
length: 3
4. 如何从数组中过滤无用值?
诸如0、undefined、null、false、空字符串""等值,可通过以下技巧轻松过滤。
const array = [3, 0, 6, 7, '', false];
array.filter(Boolean);
// Output
(3) [3, 6, 7]
5. 利用逻辑运算符处理多种条件
若希望减少if...else或switch语句的嵌套层级,可尝试使用逻辑运算符AND/OR。
function doSomething(arg1){
arg1 = arg1 || 10;
// set arg1 to 10 as a default if it's not already set
return arg1;
}
let foo = 10;
foo === 10 && doSomething();
// is the same thing as if (foo == 10) then doSomething();
// Output: 10
foo === 5 || doSomething();
// is the same thing as if (foo != 5) then doSomething();
// Output: 10
6. 删除重复值
您可能曾在for循环中使用indexOf()(返回首个匹配索引)或较新的includes()(返回布尔值true/false)来查找或删除重复项。此处提供两种更快捷的方法。
const array = [5,4,7,8,9,2,7,5];
array.filter((item,idx,arr) => arr.indexOf(item) === idx);
// or
const nonUnique = [...new Set(array)];
// Output: [5, 4, 7, 8, 9, 2]
7. 创建计数器对象或Map
解决某些问题时,常需创建计数器对象或Map,以变量为键、频率或出现次数为值来追踪变量。
let string = 'kapilalipak';
const table={};
for(let char of string) {
table[char]=table[char]+1 || 1;
}
// Output
{k: 2, a: 3, p: 2, i: 2, l: 2}
对象计数与Map计数示例
const countMap = new Map();
for (let i = 0; i < string.length; i++) {
if (countMap.has(string[i])) {
countMap.set(string[i], countMap.get(string[i]) + 1);
} else {
countMap.set(string[i], 1);
}
}
// Output
Map(5) {"k" => 2, "a" => 3, "p" => 2, "i" => 2, "l" => 2}
8. 三元运算符的妙用
您可以使用三元运算符来避免多层嵌套的if...elseif...elseif结构。
function Fever(temp) {
return temp > 97 ? 'Visit Doctor!'
: temp < 97 ? 'Go Out and Play!!'
: temp === 97 ? 'Take Some Rest!';
}
// Output
Fever(97): "Take Some Rest!"
Fever(100): "Visit Doctor!"
9. 传统for循环相比其他循环方式更快
for循环和for...in循环默认会获取索引,但您可以直接使用arr[index]。
由于for...in也接受非数字键,因此建议避免使用它。
forEach和for...of可直接获取元素。
forEach也可获取索引,但for...of不支持此功能。
10. 合并两个对象
在日常工作中,我们经常需要合并多个对象。
const user = {
name: 'Kapil Raghuwanshi',
gender: 'Male'
};
const college = {
primary: 'Mani Primary School',
secondary: 'Lass Secondary School'
};
const skills = {
programming: 'Extreme',
swimming: 'Average',
sleeping: 'Pro'
};
const summary = {...user, ...college, ...skills};
// Output
gender: "Male"
name: "Kapil Raghuwanshi"
primary: "Mani Primary School"
programming: "Extreme"
secondary: "Lass Secondary School"
sleeping: "Pro"
swimming: "Average"
11. 箭头函数
箭头函数表达式是传统函数表达式的紧凑替代方案,但存在局限性,并非适用于所有场景。由于其采用词法作用域(父级作用域),没有自己的this和arguments,因此它们引用的是定义时的环境。
const person = {
name: 'Kapil',
sayName() {
return this.name;
}
}
person.sayName();
// Output
"Kapil"
箭头函数改写示例
const person = {
name: 'Kapil',
sayName() {
return this.name;
}
}
person.sayName();
// Output
"Kapil"
12. 可选链操作符
如果?之前的值为undefined或null,可选链操作符将停止评估并返回undefined。
const user = {
employee: {
name: "Kapil"
}
};
user.employee?.name;
// Output: "Kapil"
user.employ?.name;
// Output: undefined
user.employ.name
// Output: VM21616:1 Uncaught TypeError: Cannot read property 'name' of undefined
13. 打乱数组顺序
使用内置的Math.random()方法即可实现。
const list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
list.sort(() => {
return Math.random() - 0.5;
});
// Output
(9) [2, 5, 1, 6, 9, 8, 4, 3, 7]
// Call it again
(9) [4, 1, 7, 5, 3, 8, 2, 9, 6]
14. 空值合并运算符
空值合并运算符(??)是一个逻辑运算符,当其左侧操作数为null或undefined时,返回右侧操作数;否则返回左侧操作数。
const foo = null ?? 'my school';
// Output: "my school"
const baz = 0 ?? 42;
// Output: 0
15. Rest与Spread运算符
那神秘的三个点……既可以是Rest也可以是Spread!
function myFun(a, b, ...manyMoreArgs) {
return arguments.length;
}
myFun("one", "two", "three", "four", "five", "six");
// Output: 6
Rest与Spread示例
const parts = ['shoulders', 'knees'];
const lyrics = ['head', ...parts, 'and', 'toes'];
lyrics;
// Output:
(5) ["head", "shoulders", "knees", "and", "toes"]
16. 默认参数
const search = (arr, low=0,high=arr.length-1) => {
return high;
}
search([1,2,3,4,5]);
// Output: 4
17. 十进制转换为二进制或十六进制
我们可以利用一些内置方法,如.toPrecision()或.toFixed()来辅助解决此类问题。
num.toString(2);
// Output: "1010"
num.toString(16);
// Output: "a"
num.toString(8);
// Output: "12"
18. 使用解构简单交换两个值
let a = 5;
let b = 8;
[a,b] = [b,a]
[a,b]
// Output
(2) [8, 5]
19. 单行回文检查
function checkPalindrome(str) {
return str == str.split('').reverse().join('');
}
checkPalindrome('naman');
// Output: true
20. 将对象属性转换为数组
使用Object.entries()、Object.keys()和Object.values()即可实现。
const obj = { a: 1, b: 2, c: 3 };
Object.entries(obj);
// Output
(3) [Array(2), Array(2), Array(2)]
0: (2) ["a", 1]
1: (2) ["b", 2]
2: (2) ["c", 3]
length: 3
Object.keys(obj);
(3) ["a", "b", "c"]
Object.values(obj);
(3) [1, 2, 3]
总结
以上就是我整理的技巧,希望大家关注本站其他文章!
5款主流JS在线运行工具对比:CodePen、JSFiddle与StackBlitz怎么选
2026-11-05 17:04:04
JavaScript入门书籍避坑:这些书不适合初学者
2026-11-05 16:31:15
JS使用Math.round实现保留两位小数的原理与代码
2026-11-05 15:35:55
JavaScript 原生 Date 对象怎么实现日期加减
2026-11-05 14:30:00
JavaScript函数定义的三种方式:声明、表达式与箭头函数
2026-11-05 13:50:55
