代码优化技巧
带有多个条件的 if 语句
把多个值放在一个数组中,然后调用数组的 includes 方法。
// longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
//logic
}
// shorthand
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
//logic
}
简化 if true...else
对于不包含大逻辑的 if-else 条件,可以使用下面的快捷写法。我们可以简单地使用三元运算符来实现这种简化。
// Longhand
let test: boolean;
if (x > 100) {
test = true;
} else {
test = false;
}
// Shorthand
let test = (x > 10) ? true : false;
//或者我们也可以直接用
let test = x > 10;
console.log(test);
如果有嵌套的条件,可以这么做。
let x = 300,
test2 = (x > 100) ? 'greater than 100' : (x < 50) ? 'less 50' : 'between 50 and 100';
console.log(test2); // "greater than 100"
声明变量
当我们想要声明两个具有相同的值或相同类型的变量时,可以使用这种简写。
//Longhand
let test1;
let test2 = 1;
//Shorthand
let test1, test2 = 1;
null、undefined 和空值检查
当我们创建了新变量,有时候想要检查引用的变量是不是为非 null 或 undefined。
JavaScript 确实有一个很好的快捷方式来实现这种检查。
// Longhand
if (test1 !== null || test1 !== undefined || test1 !== '') {
let test2 = test1;
}
// Shorthand
let test2 = test1 || '';
null 检查和默认赋值
let test1 = null,
test2 = test1 || '';
console.log("null check", test2); // 输出 ""
undefined 检查和默认赋值
let test1 = undefined,
test2 = test1 || '';
console.log("undefined check", test2); // 输出 ""
一般值检查
let test1 = 'test',
test2 = test1 || '';
console.log(test2); // 输出: 'test'
另外,对于上述的3点,都可以使用?? 操作符。
如果左边值为 null 或 undefined,就返回右边的值。默认情况下,它将返回左边的值。
const test= null ?? 'default';
console.log(test);
// 输出结果: "default"
const test1 = 0 ?? 2;
console.log(test1);
// 输出结果: 0
给多个变量赋值
当我们想给多个不同的变量赋值时,这种技巧非常有用。
// Longhand
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;
// Shorthand
let [test1, test2, test3] = [1, 2, 3];
简便的赋值操作符
在编程过程中,我们要处理大量的算术运算符。这是 JavaScript 变量赋值操作符的有用技巧之一。
// Longhand
test1 = test1 + 1;
test2 = test2 - 1;
test3 = test3 * 20;
// Shorthand
test1++;
test2--;
test3 *= 20;
if 判断值是否存在
这是我们都在使用的一种常用的简便技巧,在这里仍然值得再提一下。
// Longhand
if (test1 === true) or if (test1 !== "") or if (test1 !== null)
// Shorthand //检查空字符串、null或者undefined
if (test1)
注意:如果 test1 有值,将执行 if 之后的逻辑,这个操作符主要用于 null 或 undefinded 检查。
用于多个条件判断的 && 操作符
如果只在变量为 true 时才调用函数,可以使用 && 操作符。
// Longhand
if (test1) {
callMethod();
}
// Shorthand
test1 && callMethod();
for each 循环
这是一种常见的循环简化技巧。
// Longhand
for (var i = 0; i < testData.length; i++)
// Shorthand
for (let i in testData) or for (let i of testData)
遍历数组的每一个变量。
function testData(element, index, array) {
console.log('test[' + index + '] = ' + element);
}
[11, 24, 32].forEach(testData);
// logs: test[0] = 11, test[1] = 24, test[2] = 32
比较后返回
我们也可以在 return 语句中使用比较,它可以将 5 行代码减少到 1 行。
// Longhand
let test;
function checkReturn() {
if (!(test === undefined)) {
return test;
} else {
return callMe('test');
}
}
var data = checkReturn();
console.log(data); //output test
function callMe(val) {
console.log(val);
}
// Shorthand
function checkReturn() {
return test || callMe('test');
}
箭头函数
// Longhand
function add(a, b) {
return a + b;
}
// Shorthand
const add = (a, b) => a + b;
简短的函数调用
我们可以使用三元操作符来实现多个函数调用。
// Longhand
function test1() {
console.log('test1');
};
function test2() {
console.log('test2');
};
var test3 = 1;
if (test3 == 1) {
test1();
} else {
test2();
}
// Shorthand
(test3 === 1? test1:test2)();
switch 简化
我们可以将条件保存在键值对象中,并根据条件来调用它们。
// Longhand
switch (data) {
case 1:
test1();
break;
case 2:
test2();
break;
case 3:
test();
break;
// ...
}
// Shorthand
var data = {
1: test1,
2: test2,
3: test
};
data[something] && data[something]();
隐式返回
通过使用箭头函数,我们可以直接返回值,不需要 return 语句。
// longhand
function calculate(diameter) {
return Math.PI * diameter
}
// shorthand
calculate = diameter => (
Math.PI * diameter;
)
指数表示法
// Longhand
for (var i = 0; i < 10000; i++) { ... }
// Shorthand
for (var i = 0; i < 1e4; i++) { ... }
默认参数值
// Longhand
function add(test1, test2) {
if (test1 === undefined)
test1 = 1;
if (test2 === undefined)
test2 = 2;
return test1 + test2;
}
// shorthand
add = (test1 = 1, test2 = 2) => (test1 + test2);
add() //输出结果: 3
延展操作符简化
// longhand
// 使用concat连接数组
const data = [1, 2, 3];
const test = [4 ,5 , 6].concat(data);
// shorthand
// 连接数组
const data = [1, 2, 3];
const test = [4 ,5 , 6, ...data];
console.log(test); // [ 4, 5, 6, 1, 2, 3]
我们也可以使用延展操作符进行克隆。
// longhand
// 克隆数组
const test1 = [1, 2, 3];
const test2 = test1.slice()
// shorthand
//克隆数组
const test1 = [1, 2, 3];
const test2 = [...test1];
模板字面量
如果你厌倦了使用 + 将多个变量连接成一个字符串,那么这个简化技巧将让你不再头痛。
// longhand
const welcome = 'Hi ' + test1 + ' ' + test2 + '.'
// shorthand
const welcome = `Hi ${test1} ${test2}`;
跨行字符串
当我们在代码中处理跨行字符串时,可以这样做。
//longhand
const data = 'abc abc abc abc abc abc\n\t'
+ 'test test,test test test test\n\t'
//shorthand
const data = `abc abc abc abc abc abc
test test,test test test test`
对象属性赋值
let test1 = 'a';
let test2 = 'b';
// Longhand
let obj = {test1: test1, test2: test2};
// Shorthand
let obj = {test1, test2};
将字符串转成数字
// Longhand
let test1 = parseInt('123');
let test2 = parseFloat('12.3');
// Shorthand
let test1 = +'123';
let test2 = +'12.3';
解构赋值
// longhand
const test1 = this.data.test1;
const test2 = this.data.test2;
const test2 = this.data.test3;
// shorthand
const { test1, test2, test3 } = this.data;
数组 find 简化
当我们有一个对象数组,并想根据对象属性找到特定对象,find 方法会非常有用。
const data = [{
type: 'test1',
name: 'abc'
},
{
type: 'test2',
name: 'cde'
},
{
type: 'test1',
name: 'fgh'
},
]
function findtest1(name) {
for (let i = 0; i < data.length; ++i) {
if (data[i].type === 'test1' && data[i].name === name) {
return data[i];
}
}
}
//Shorthand
filteredData = data.find(data => data.type === 'test1' && data.name === 'fgh');
console.log(filteredData); // { type: 'test1', name: 'fgh' }
indexOf 的按位操作简化
在查找数组的某个值时,我们可以使用 indexOf() 方法。但有一种更好的方法,让我们来看一下这个例子。
// longhand
if (arr.indexOf(item) > -1) { // item found
}
if (arr.indexOf(item) === -1) { // item not found
}
// shorthand
if (~arr.indexOf(item)) { // item found
}
if (!~arr.indexOf(item)) { // item not found
}
按位 ( ~ ) 运算符将返回 true(-1 除外),反向操作只需要!~。另外,也可以使用 include() 函数。
if (arr.includes(item)) {
// 如果找到项目,则为true
}
Object.entries()
这个方法可以将对象转换为对象数组。
const data = { test1: 'abc', test2: 'cde', test3: 'efg' };
const arr = Object.entries(data);
console.log(arr);
/** Output:
[ [ 'test1', 'abc' ],
[ 'test2', 'cde' ],
[ 'test3', 'efg' ]
]
**/
Object.values()
这也是 ES8 中引入的一个新特性,它的功能类似于 Object.entries(),只是没有键。
const data = { test1: 'abc', test2: 'cde' };
const arr = Object.values(data);
console.log(arr);
/** Output:
[ 'abc', 'cde']
**/
双重按位操作
// Longhand
Math.floor(1.9) === 1 // true
// Shorthand
~~1.9 === 1 // true
重复字符串多次
为了重复操作相同的字符,我们可以使用 for 循环,但其实还有一种简便的方法。
// longhand
let test = '';
for(let i = 0; i < 5; i ++) {
test += 'test ';
}
console.log(str); // test test test test test
// shorthand
'test '.repeat(5);
查找数组的最大值和最小值
const arr = [1, 2, 3];
Math.max(…arr); // 3
Math.min(…arr); // 1
获取字符串的字符
let str = 'abc';
//Longhand
str.charAt(2); // c
// Shorthand
str[2]; // c
指数幂简化
// longhand
Math.pow(2,3); // 8
// shorthand
2**3 // 8
用??代替||,用于判断运算符左侧的值为null或undefined时,才返回右侧的值
??运算符是 ES2020 引入,也被称为null判断运算符( Nullish coalescing operator)
它的行为类似||,但是更严
||运算符是左边是空字符串或false或0等falsy值,都会返回后侧的值。而??必须运算符左侧的值为null或undefined时,才会返回右侧的值。因此0||1的结果为1,0??1的结果为0
const response = {
settings: {
nullValue: null,
height: 400,
animationDuration: 0,
headerText: '',
showSplashScreen: false
}
};
const undefinedValue = response.settings.undefinedValue ?? 'some other default'; // result: 'some other default'
const nullValue = response.settings.nullValue ?? 'some other default'; // result: 'some other default'
const headerText = response.settings.headerText ?? 'Hello, world!'; // result: ''
const animationDuration = response.settings.animationDuration ?? 300; // result: 0
const showSplashScreen = response.settings.showSplashScreen ?? true; // result: false
使用?.简化&&和三元运算符
?.也是ES2020 引入,有人称为链判断运算符(optional chaining operator)
?.直接在链式调用的时候判断,判断左侧的对象是否为null或undefined,如果是的,就不再往下运算,返回undefined,如果不是,则返回右侧的值
var street = user.address && user.address.street;
var fooInput = myForm.querySelector('input[name=foo]')
var fooValue = fooInput ? fooInput.value : undefined
// 简化
var street = user.address?.street
var fooValue = myForm.querySelector('input[name=foo]')?.value
- 注:常见写法
- obj?.prop 对象属性
- obj?.[expr] 对象属性
- func?.(...args) 函数或对象方法的调用
使用动态导入import()实现按需加载(优化静态import)
我们可以使用 import 语句初始化的加载依赖项
import defaultExport from "module-name";
import * as name from "module-name";
但是静态引入的import 语句需要依赖于 type="module" 的script标签,而且有的时候我们希望可以根据条件来按需加载模块,比如以下场景:
- 当静态导入的模块很明显的降低了代码的加载速度且被使用的可能性很低,或者并不需要马上使用它
- 当静态导入的模块很明显的占用了大量系统内存且被使用的可能性很低
- 当被导入的模块,在加载时并不存在,需要异步获取
- 当被导入的模块有副作用,这些副作用只有在触发了某些条件才被需要时
这个时候我们就可以使用动态引入import(),它跟函数一样可以用于各种地方,返回的是一个 promise
基本使用如下两种形式
//形式 1
import('/modules/my-module.js')
.then((module) => {
// Do something with the module.
});
//形式2
let module = await import('/modules/my-module.js');
使用顶层 await(top-level await)简化 async 函数
其实上面的代码就有用到
let module = await import('/modules/my-module.js');
顶层 await 允许开发者在 async 函数外部使用 await 字段
//以前
(async function () {
await Promise.resolve(console.log('🎉'));
// → 🎉
})();
//简化后
await Promise.resolve(console.log('🎉'));
使用String.prototype.replaceAll()简化replace一次性替换所有子字符串
String.prototype.replaceAll()用法与String.prototype.replace()类似
但是replace仅替换第一次出现的子字符串,而replaceAll会替换所有
例如需要替换所有a为A:
// 以前
console.log('aaa'.replace(/a/g,'A')) //AAA
// 简化后
console.log('aaa'.replaceAll('a','A')) //AAA
使用Proxy替代Object.defineProperty
为什么使用 Proxy 替代 Object.defineProperty,简单总结Proxy的几点优势
- Proxy 是对整个对象的代理,而 Object.defineProperty 只能代理某个属性
- 对象上新增属性,Proxy 可以监听到,Object.defineProperty 不能
- 数组新增修改,Proxy 可以监听到,Object.defineProperty 不能
- 若对象内部属性要全部递归代理,Proxy 可以只在调用的时候递归,而 Object.definePropery 需要一次完成所有递归,性能比 Proxy 差
使用也很简单,Proxy本质是构造函数,通过new即可产生对象,它接收两个参数:
- target表示的就是要拦截(代理)的目标对象
- handler是用来定制拦截行为(13种)
例如响应式reactive的基本实现:
function reactive(obj) {
return new Proxy(obj, {
get(target, key) {
// 可以做依赖收集
track(target, key)
return target[key]
},
set(target, key, val) {
target[key] = val
// 触发依赖
trigger(target, key)
}
})
}
Promise.any快速获取一组Promise实例中第一个fulfilled的promise
Promise.any 接收一组Promise实例作为参数
- 只要其中的一个 promise 成功,就返回那个已经成功的 promise
- 如果这组可迭代对象中,没有一个 promise 成功,就返回一个失败的 promise 和 AggregateError 类型的实例
try {
nst first = await Promise.any(promises);
// Any of the promises was fulfilled.
} catch (error) {
// All of the promises were rejected.
}
Promise.any(promises).then(
(first) => {
// Any of the promises was fulfilled.
},
(error) => {
// All of the promises were rejected.
}
);
使用BigInt支持大整数计算问题
ES2020引入了一种新的数据类型 BigInt,用来表示任意位数的整数
// 超过 53 个二进制位的数值(相当于 16 个十进制位),无法保持精度
Math.pow(2, 53) === Math.pow(2, 53) + 1 // true
// BigInt
BigInt(Math.pow(2, 53)) === BigInt(Math.pow(2, 53)) + BigInt(1) // false
除了使用BigInt来声明一个大整数,还可以使用数字后面加n的形式,如
1234 // 普通整数
1234n // BigInt
需要了解BigInt数字操作时的支持情况,以免踩坑
操作 | 是否支持 |
---|---|
单目 (+) 运算符 | N |
+、*、-、**、% 运算符 | Y |
\ 除法运算符 | 带小数的运算会被取整 |
>>> 无符号右移位操作符 | N |
其他位移操作符 | Y |
与 Number 混合运算 | N(必须转换为同类型) |
Math 对象方法 | N |
Number 与 BigInt 比较(排序) | Y(宽松相等 ==) |
Boolean 表现 | 类型 Number 对象 |
JSON 中使用 | N |
使用Array.prototype.at()简化arr.length
Array.prototype.at()接收一个正整数或者负整数作为参数,表示获取指定位置的成员
参数正数就表示顺数第几个,负数表示倒数第几个,这可以很方便的某个数组末尾的元素
var arr = [1, 2, 3, 4, 5]
// 以前获取最后一位
console.log(arr[arr.length-1]) //5
// 简化后
console.log(arr.at(-1)) // 5
使用哈希前缀#将类字段设为私有
在类中通过哈希前缀#标记的字段都将被私有,子类实例将无法继承
class ClassWithPrivateField {
#privateField;
#privateMethod() {
return 'hello world';
}
constructor() {
this.#privateField = 42;
}
}
const instance = new ClassWithPrivateField()
console.log(instance.privateField); //undefined
console.log(instance.privateMethod); //undefined