一、!!和!!!的深入理解
1. !!(双重非)操作符
将任意值强制转换为布尔类型,等效于 Boolean() 函数。
转换规则:
-
假值(
null、undefined、0、''、NaN、false)→false -
其他值 →
true(包括空数组[]、空对象{}、函数等)
典型应用场景:
// 判断对象是否存在
const user = null;
console.log(!!user); // false
// 简化条件判断
if (!!items.length) { /* 处理非空数组 */ }
// 在Vue项目中判断数据状态
const isLoggedIn = !!user.token;
2. !!!(三重非)操作符
先通过!!转换为布尔值,再取反一次,等效于 !Boolean(值)。
典型应用场景:
// 简化反向逻辑判断 const isEmpty = !!!value; // 等效于 value === null || value === undefined || value === '' // 在Vue中处理加载状态 loading.value = !!!data; // 数据存在时隐藏加载状态
二、JavaScript 基础实用技巧
1. 空值合并与默认值处理
// 传统写法(缺陷:0、''、false 也会被替换)
const name = user.name || '默认名称';
// 推荐写法(仅替换 null/undefined)
const name = user.name ?? '默认名称';
// 对象解构默认值
const { age = 18, address = {} } = user;
2. 可选链操作符(Optional Chaining)
// 传统写法 const city = user && user.address && user.address.city; // 简洁写法 const city = user?.address?.city; // 结合空值合并 const city = user?.address?.city ?? '未知城市';
3. 快速数值转换
const strNum = '123'; const num = +strNum; // 等效于 Number(strNum) // 取整技巧 const floatNum = 3.14; const intNum = ~~floatNum; // 双波浪号取整,等效于 Math.floor(3.14)
4. 数组去重
const arr = [1, 2, 2, 3, 3, 3]; const uniqueArr = [...new Set(arr)]; // [1, 2, 3]
5. 交换变量值
let a = 1, b = 2; // 传统写法 const temp = a; a = b; b = temp; // 简洁写法 [a, b] = [b, a];
三、函数与作用域技巧
1. 函数参数默认值
// 传统写法
function greet(name) {
name = name || 'Guest';
console.log(`Hello, ${name}`);
}
// 推荐写法
function greet(name = 'Guest') {
console.log(`Hello, ${name}`);
}
2. 箭头函数简化
// 传统函数
const sum = function(a, b) {
return a + b;
};
// 箭头函数
const sum = (a, b) => a + b;
3. 立即执行函数(IIFE)
// ES5常用
(function() {
const privateVar = '私有变量';
// 私有作用域
})();
// ES6模块替代方案
{
const privateVar = '私有变量';
// 块级作用域
}
四、对象与数组操作技巧
1. 对象浅拷贝
const obj = { a: 1, b: 2 };
const clone = { ...obj }; // 展开语法
// 等效于 Object.assign({}, obj)
2. 数组合并
const arr1 = [1, 2]; const arr2 = [3, 4]; const merged = [...arr1, ...arr2]; // [1, 2, 3, 4]
3. 数组过滤与映射
const numbers = [1, 2, 3, 4, 5]; // 过滤偶数并翻倍 const result = numbers .filter(n => n % 2 === 0) // [2, 4] .map(n => n * 2); // [4, 8]
4. 解构赋值高级用法
// 对象解构重命名
const { name: userName, age: userAge } = user;
// 数组解构
const [first, second, ...rest] = [1, 2, 3, 4, 5];
五、异步编程技巧
1. 异步函数简化
// 传统Promise
fetchData()
.then(data => processData(data))
.catch(error => console.error(error));
// 推荐:async/await
async function fetchAndProcess() {
try {
const data = await fetchData();
const result = processData(data);
} catch (error) {
console.error(error);
}
}
2. 并行请求处理
// 多个API并行请求
async function fetchAll() {
const [user, posts] = await Promise.all([
fetchUser(),
fetchPosts()
]);
return { user, posts };
}
3. 防抖与节流
// 防抖函数(避免频繁触发)
const debounce = (fn, delay) => {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
};
// 节流函数(限制执行频率)
const throttle = (fn, limit) => {
let inThrottle;
return (...args) => {
if (!inThrottle) {
fn(...args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
};
六、性能优化技巧
1. 延迟加载(懒加载)
// 按需加载模块
const loadHeavyModule = async () => {
const heavyModule = await import('./heavy-module.js');
heavyModule.init();
};
// 点击按钮时加载
button.addEventListener('click', loadHeavyModule);
2. 循环优化
// 传统for循环(性能最优) for (let i = 0, len = arr.length; i
3. 事件委托
// 父元素监听,子元素触发
parentElement.addEventListener('click', (e) => {
if (e.target.matches('.child-element')) {
// 处理子元素点击事件
}
});
七、调试与错误处理
1. 控制台美化输出
// 带颜色的日志
console.log('%c重要信息', 'color: blue; font-weight: bold');
// 表格形式输出
console.table([{ name: '张三', age: 20 }, { name: '李四', age: 25 }]);
2. 错误边界(Error Boundary)
// 自定义错误捕获函数
window.onerror = function(message, source, lineno, colno, error) {
// 记录错误信息
logError({ message, source, lineno, colno, error });
return true; // 阻止错误冒泡
};
3. 断言(Assertion)
function assert(condition, message) {
if (!condition) {
throw new Error(message || 'Assertion failed');
}
}
// 使用示例
assert(typeof value === 'number', 'value必须是数字');
八、类型检查与转换
1. 类型安全检查
// 检查数组 Array.isArray([]); // true // 检查空对象 const isEmptyObject = obj => obj && typeof obj === 'object' && !Object.keys(obj).length; // 检查null/undefined const isNullOrUndefined = val => val == null; // 注意:使用==而非===
2. 安全的类型转换
// 字符串转数字
const num = parseInt('123', 10); // 第二个参数必须为10
// 安全的JSON解析
const parseJSON = (str) => {
try {
return JSON.parse(str);
} catch (e) {
return null;
}
};
到此这篇关于针对初学者的JavaScript八种类型实用小技巧总结的文章就介绍到这了,更多相关JavaScript类型技巧内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!
