以下是 40 个常用的 JavaScript 使用技巧,包含案例代码和解释:
const arr = [1, 2, 2, 3, 4, 4, 5];
const uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // [1, 2, 3, 4, 5]
解释:Set
对象是一种无序且唯一的数据结构,使用扩展运算符 ...
将 Set
转换回数组,从而实现去重。
const arr1 = [1, 2];
const arr2 = [3, 4];
const arr3 = [5, 6];
const mergedArr = [...arr1, ...arr2, ...arr3];
console.log(mergedArr); // [1, 2, 3, 4, 5, 6]
解释:使用扩展运算符可以轻松地将多个数组合并成一个新数组。
const arr = [1, 2, 3];
const [a, b, c] = arr;
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
解释:通过解构赋值,可以方便地从数组中提取值并赋给变量。
const obj = { name: 'John', age: 30 };
const { name, age } = obj;
console.log(name); // 'John'
console.log(age); // 30
解释:可以从对象中提取属性并赋给变量。
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a); // 2
console.log(b); // 1
解释:使用数组解构赋值可以简洁地交换两个变量的值。
const obj = {
person: {
name: 'John'
}
};
const name = obj?.person?.name;
console.log(name); // 'John'
解释:可选链操作符 ?.
可以避免在访问嵌套对象属性时出现 TypeError
。
const value = null;
const result = value ?? 'default';
console.log(result); // 'default'
解释:空值合并操作符 ??
用于在变量为 null
或 undefined
时提供默认值。
const numbers = [1, 2, 3];
const squared = numbers.map(num => num * num);
console.log(squared); // [1, 4, 9]
解释:箭头函数是一种简洁的函数定义方式,适用于简单的函数逻辑。
function greet(name = 'Guest') {
console.log(`Hello, ${name}!`);
}
greet(); // 'Hello, Guest!'
greet('John'); // 'Hello, John!'
解释:可以为函数参数提供默认值,当调用函数时未传递该参数时,将使用默认值。
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
console.log(obj2); // { a: 1, b: 2, c: 3 }
解释:使用扩展运算符可以将一个对象的属性展开到另一个对象中。
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4]
解释:filter
方法用于创建一个新数组,其中包含满足指定条件的元素。
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
解释:map
方法用于创建一个新数组,其中每个元素都是原数组中对应元素经过某种处理后的结果。
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 10
解释:reduce
方法用于将数组元素归约为一个值。
const numbers = [1, 2, 3, 4, 5];
const found = numbers.find(num => num > 3);
console.log(found); // 4
解释:find
方法用于查找数组中第一个满足指定条件的元素。
const numbers = [1, 2, 3, 4, 5];
const index = numbers.findIndex(num => num > 3);
console.log(index); // 3
解释:findIndex
方法用于查找数组中第一个满足指定条件的元素的索引。
const str = '123';
const num = +str;
console.log(num); // 123
解释:使用一元加号 +
可以将字符串转换为数字。
const num = 123;
const str = num.toString();
console.log(str); // '123'
解释:toString
方法可以将数字转换为字符串。
const arr = [1, 2, 3];
const isArray = Array.isArray(arr);
console.log(isArray); // true
解释:Array.isArray
方法用于检查一个变量是否为数组。
const obj = { a: 1 };
const isObject = typeof obj === 'object' && obj!== null;
console.log(isObject); // true
解释:使用 typeof
检查变量类型,并排除 null
的情况。
const key = 'name';
const value = 'John';
const obj = { [key]: value };
console.log(obj); // { name: 'John' }
解释:使用方括号语法可以动态创建对象属性。
function greet() {
console.log('Hello!');
}
setTimeout(greet, 2000); // 2 秒后输出 'Hello!'
解释:setTimeout
方法用于在指定的时间后执行一个函数。
function greet() {
console.log('Hello!');
}
setInterval(greet, 2000); // 每 2 秒输出一次 'Hello!'
解释:setInterval
方法用于每隔指定的时间执行一次函数。
function greet() {
console.log('Hello!');
}
const intervalId = setInterval(greet, 2000);
clearInterval(intervalId); // 取消定时任务
解释:使用 clearInterval
方法可以取消由 setInterval
创建的定时任务。
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1 };
console.log(obj2); // { a: 1, b: 2 }
解释:使用扩展运算符可以实现对象的浅拷贝。
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = JSON.parse(JSON.stringify(obj1));
console.log(obj2); // { a: 1, b: { c: 2 } }
解释:使用 JSON.parse
和 JSON.stringify
可以实现对象的深拷贝,但这种方法有局限性,不能处理函数、正则表达式等特殊对象。
const obj = { name: 'John' };
const hasName = 'name' in obj;
console.log(hasName); // true
解释:使用 in
运算符可以检查对象是否有某个属性。
const obj = { a: 1, b: 2 };
const keys = Object.keys(obj);
console.log(keys); // ['a', 'b']
解释:Object.keys
方法用于获取对象的所有属性名。
const obj = { a: 1, b: 2 };
const values = Object.values(obj);
console.log(values); // [1, 2]
解释:Object.values
方法用于获取对象的所有属性值。
const obj = { a: 1, b: 2 };
const entries = Object.entries(obj);
console.log(entries); // [['a', 1], ['b', 2]]
解释:Object.entries
方法用于获取对象的所有属性键值对。
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog('Buddy');
dog.speak(); // 'Buddy barks.'
解释:使用 extends
关键字可以实现类的继承。
// module.js
export const message = 'Hello!';
// main.js
import { message } from './module.js';
console.log(message); // 'Hello!'
解释:使用 export
关键字导出模块中的变量或函数,使用 import
关键字导入模块。
const age = 20;
const canVote = age >= 18? 'Yes' : 'No';
console.log(canVote); // 'Yes'
解释:三元运算符是一种简洁的条件判断语句。
const name = null;
const displayName = name || 'Guest';
console.log(displayName); // 'Guest'
解释:使用逻辑或 ||
运算符可以实现短路求值,当第一个值为假时,返回第二个值。
function add(a, b) {
if (b === undefined) {
return function (b) {
return a + b;
};
}
return a + b;
}
const add5 = add(5);
console.log(add5(3)); // 8
解释:函数柯里化是指将一个多参数函数转换为一系列单参数函数。
function debounce(func, delay) {
let timer;
return function () {
const context = this;
const args = arguments;
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(context, args);
}, delay);
};
}
function search() {
console.log('Searching...');
}
const debouncedSearch = debounce(search, 500);
window.addEventListener('input', debouncedSearch);
解释:防抖函数用于限制函数的调用频率,在一定时间内只执行最后一次调用。
function throttle(func, limit) {
let inThrottle;
return function () {
const context = this;
const args = arguments;
if (!inThrottle) {
func.apply(context, args);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
}
};
}
function scroll() {
console.log('Scrolling...');
}
const throttledScroll = throttle(scroll, 500);
window.addEventListener('scroll', throttledScroll);
解释:节流函数用于限制函数的调用频率,在一定时间内只执行一次调用。
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
fetchData();
解释:异步函数使用 async/await
语法,可以更方便地处理异步操作。
function* generateNumbers() {
let i = 0;
while (true) {
yield i++;
}
}
const generator = generateNumbers();
console.log(generator.next().value); // 0
console.log(generator.next().value); // 1
解释:生成器函数使用 function*
定义,使用 yield
关键字暂停和恢复函数执行。
const ul = document.querySelector('ul');
ul.addEventListener('click', function (event) {
if (event.target.tagName === 'LI') {
console.log('Clicked on a list item:', event.target.textContent);
}
});
解释:事件委托是指将事件监听器添加到父元素上,利用事件冒泡机制处理子元素的事件。
const randomNum = Math.floor(Math.random() * 10);
console.log(randomNum); // 0 - 9 之间的随机整数
解释:使用 Math.random()
生成 0 到 1 之间的随机小数,使用 Math.floor()
向下取整。