1. 解构赋值与变量重命名
解构赋值是一个强大的特性。你知道在赋值的时候可以给变量起别名吗?
const { prop1: newName1, prop2: newName2 } = object;
这里,我们把 prop1
和 prop2
分别重命名为 newName1
和 newName2
。
2. 使用记忆化提升性能
记忆化是一种缓存函数结果以提升性能的技巧。来看一个简单的实现:
const memoizedFunction = (function () {
const cache = {};
return function (args) {
if (!(args in cache)) {
cache[args] = computeResult(args);
}
return cache[args];
};
})();
通过缓存结果,我们避免了重复的计算。
3. 函数柯里化用于组合函数
柯里化允许创建可复用和可组合的函数。看看这个简洁的柯里化函数:
const curry = (fn, ...args) =>
args.length >= fn.length ? fn(...args) : (...moreArgs) => curry(fn, ...args, ...moreArgs);
有了它,你可以轻松地创建部分应用函数。
4. 防抖和节流
控制函数执行的频率至关重要。使用防抖和节流技术可以高效处理频繁的事件。
const debounce = (func, delay) => {
let timeoutId;
return function (...args) {
const context = this;
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(context, args);
}, delay);
};
};
const throttle = (func, interval) => {
let lastExecTime = 0;
let timeoutId;
return function (...args) {
const context = this;
const currentTime = new Date().getTime();
if (currentTime - lastExecTime >= interval) {
func.apply(context, args);
lastExecTime = currentTime;
} else {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(context, args);
lastExecTime = currentTime;
}, interval - (currentTime - lastExecTime));
}
};
};
这些技巧防止了过多的函数调用,提高了性能。
5. 动态对象键
使用方括号表示法动态创建对象键:
const dynamicKey = 'key';
const obj = { [dynamicKey]: 'value' };
当键在运行时确定时,这个特性非常有用。
6. 可选链
可选链简化了访问嵌套属性的过程,无需进行大量检查。
// 新手:
let nestedValue;
if (object && object.property && object.property.nested) {
nestedValue = object.property.nested;
} else {
nestedValue = 'default';
}
// 高手:
let nestedValue = object?.property?.nested ?? 'default';
这有助于防止“无法读取未定义的‘nested’属性”的错误,并使代码更加简洁。
7. 箭头函数
箭头函数为定义函数提供了一种简洁的语法。
// 新手:
function add(a, b) {
return a + b;
}
// 高手:
const add = (a, b) => a + b;
箭头函数特别适用于简短的匿名函数。
8. 数组解构
解构不仅适用于对象;它对于数组同样有效!
// 新手:
const array = [1, 2, 3];
const first = array[0];
const second = array[1];
// 高手:
const [first, second] = [1, 2, 3];
这使得处理数组元素变得更加直接。
9. 对象解构
与数组解构类似,这种技术用于对象。
// 新手:
const user = { name: 'John', age: 30 };
const name = user.name;
const age = user.age;
// 高手:
const { name, age } = { name: 'John', age: 30 };
使用解构来简洁地提取对象值。
10. 使用 Proxy 进行验证
使用 Proxy 对象进行输入验证。
const validator = new Proxy({}, {
set: function (target, prop, value) {
if (prop === 'age' && typeof value !== 'number') {
throw new Error('Age must be a number.');
}
target[prop] = value;
}
});
代理可以拦截并验证属性赋值,提供强大的输入控制。