一、类型与运算骚操作 (20例)
- 最短的空值检查
const name = inputName || 'Anonymous';
- 双重非位运算取整
~~3.14159;
- 异或交换变量
let a = 1, b = 2;
a ^= b; b ^= a; a ^= b;
- 利用空数组转数字0
+[];
- 快速生成0-1随机布尔值
const bool = Math.random() >= 0.5;
- 利用短路求值执行函数
condition && doSomething();
- 逗号操作符返回最后一个值
let x = (1, 2, 3);
- void 0 替代 undefined
const data = void 0;
- 快速生成序列数组
Array.from({length:5}, (_,i) => i);
- 利用对象键名唯一性去重
const unique = [...new Set(arr)];
- 字符串转数组再反转
'hello'.split('').reverse().join('');
- 数字转字符串再转数组
String(123).split('').map(Number);
- 利用位运算判断奇偶
const isEven = num => (num & 1) === 0;
- 快速浮点数转整数
3.14 | 0;
- 利用指数运算符计算幂
2 ** 3;
- 利用解构交换变量
[a, b] = [b, a];
- 生成唯一递增ID
let id = 0; const getID = () => id++;
- 利用模板字符串调用函数
const greet = (strings, name) => `Hello ${name}`;
greet`World`;
- 利用闭包缓存计算结果
const memoize = (fn) => { const cache = new Map(); return arg => cache.has(arg) ? cache.get(arg) : cache.set(arg, fn(arg)) && cache.get(arg); };
- 利用JSON进行深拷贝
const deepCopy = obj => JSON.parse(JSON.stringify(obj));
二、函数与作用域黑魔法 (15例)
- 自执行匿名函数 (IIFE)
(() => { console.log('立即执行'); })();
- 函数柯里化
const add = a => b => a + b; add(2)(3);
- 动态生成函数
const sum = new Function('a', 'b', 'return a + b');
- 绑定上下文到新对象
const bound = someFunc.bind({name: 'ctx'});
- 函数参数默认值
const greet = (name = 'Guest') => `Hello ${name}`;
- 剩余参数收集
const sum = (...nums) => nums.reduce((a,b) => a + b, 0);
- 函数属性模拟静态变量
function counter() { return ++counter.count || (counter.count = 0); }
- 利用闭包创建私有变量
function Person() { let age = 0; return { getAge: () => age, birthday: () => age++ };}
- 惰性函数定义(优化性能)
function lazyFunc() {
lazyFunc = () => '优化后的逻辑';
return lazyFunc();
}
- 函数递归自身引用
const factorial = n => n <= 1 ? 1 : n * factorial(n - 1);
- 利用arguments转数组
function logArgs() { console.log([...arguments]); }
- 闭包陷阱(循环变量问题)
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
- 解决闭包陷阱的IIFE方案
for (var i = 0; i < 3; i++) {
(function(j) { setTimeout(() => console.log(j), 100); })(i);
}
- 箭头函数绑定词法作用域
const obj = {
value: 42,
getValue: () => this.value
};
- 利用Proxy拦截函数调用
const handler = { apply: (target, thisArg, args) => { console.log('函数被调用'); return target(...args); } };
const proxiedFunc = new Proxy(() => {}, handler);
三、对象与原型链技巧 (15例)
- 对象属性名动态计算
const key = 'name';
const obj = { [key]: 'Alice' };
- 合并对象(浅层)
const merged = { ...obj1, ...obj2 };
- 对象冻结防止修改
const frozen = Object.freeze({ value: 42 });
- 检测对象是否为空
const isEmpty = obj => Object.keys(obj).length === 0;
- 对象迭代键值对
for (const [key, value] of Object.entries(obj)) { ... }
- 利用原型链实现继承
function Parent() {}
function Child() {}
Child.prototype = Object.create(Parent.prototype);
- 修改原型链添加方法(慎用!)
Array.prototype.last = function() { return this[this.length-1]; };
[1,2,3].last();
- 利用Object.defineProperty定义属性
const obj = {};
Object.defineProperty(obj, 'readOnlyProp', { value: 42, writable: false });
- 检测属性存在性
'toString' in {};
obj.hasOwnProperty('key');
- 利用Symbol作为唯一键
const privateKey = Symbol('internal');
const obj = { [privateKey]: 'secret' };
- 使用WeakMap存储私有数据
const privates = new WeakMap();
function MyClass() { privates.set(this, { data: 42 }); }
MyClass.prototype.getData = function() { return privates.get(this).data; };
- 对象解构别名
const { name: userName, age } = { name: 'Alice', age: 30 };
- 对象属性简写
const name = 'Alice';
const user = { name };
- 链式判断运算符
const street = user?.address?.street;
- 可选链调用函数
obj.someMethod?.();
四、浏览器API骚操作 (20例)
- 拦截XHR请求
const originalXHR = window.XMLHttpRequest;
window.XMLHttpRequest = class extends originalXHR {
open(...args) { console.log('请求:', args); super.open(...args); }
};
- 监听所有点击事件
document.addEventListener('click', e => console.log('点击:', e.target));
- 使用事件委托优化性能
document.querySelector('#list').addEventListener('click', e => {
if (e.target.matches('li.item')) { console.log('Item被点击'); }
});
- 动态加载脚本
const script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery.min.js';
document.head.appendChild(script);
- 快速清空DOM节点
element.innerHTML = '';
while (element.firstChild) element.removeChild(element.firstChild);
- 使用文档片段批量插入
const fragment = document.createDocumentFragment();
items.forEach(item => fragment.appendChild(createElement(item)));
container.appendChild(fragment);
- 获取元素计算样式
const style = window.getComputedStyle(element);
const width = style.getPropertyValue('width');
- 监听CSS动画结束
element.addEventListener('animationend', () => { ... });
- 全屏API控制
document.documentElement.requestFullscreen();
document.exitFullscreen();
- 获取用户剪贴板数据
navigator.clipboard.readText().then(text => console.log(text));
- 写入剪贴板
navigator.clipboard.writeText('要复制的文本');
- 监听页面可见性变化
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') { ... }
});
- 使用Geolocation获取位置
navigator.geolocation.getCurrentPosition(pos => {
const { latitude, longitude } = pos.coords;
});
- 使用WebSocket实时通信
const socket = new WebSocket('ws://example.com');
socket.onmessage = event => { console.log('收到消息:', event.data); };
- 使用Fetch发起请求
fetch('/api/data')
.then(res => res.json())
.then(data => console.log(data));
- 使用AbortController取消请求
const controller = new AbortController();
fetch(url, { signal: controller.signal });
controller.abort();
- 使用Intersection Observer懒加载
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.src = entry.target.dataset.src;
observer.unobserve(entry.target);
}
});
});
images.forEach(img => observer.observe(img));
- 使用MutationObserver监听DOM变化
const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => { ... });
});
observer.observe(targetNode, { childList: true, subtree: true });
- 使用Performance API测量性能
performance.mark('start');
performance.mark('end');
performance.measure('耗时', 'start', 'end');
const duration = performance.getEntriesByName('耗时')[0].duration;
- 使用Canvas绘制图像
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 100, 100);
五、异步与并发黑科技 (15例)
- Promise链式调用
fetchData()
.then(processData)
.then(data => saveData(data))
.catch(handleError);
- 并行执行多个Promise
Promise.all([promise1, promise2]).then(([res1, res2]) => { ... });
- Promise超时处理
const timeout = (ms) => new Promise((_, reject) =>
setTimeout(() => reject(new Error('超时')), ms)
);
Promise.race([fetchData(), timeout(5000)]);
- Async/Await简化异步
async function loadData() {
try {
const data = await fetchData();
const processed = await processData(data);
return processed;
} catch (error) {
handleError(error);
}
}
- 生成器函数处理异步流程
function* asyncGenerator() {
const data = yield fetchData();
const result = yield processData(data);
return result;
}
- 使用Web Workers多线程
const worker = new Worker('worker.js');
worker.postMessage(data);
worker.onmessage = e => console.log(e.data);
- SharedArrayBuffer多线程共享内存
const buffer = new SharedArrayBuffer(16);
const view = new Int32Array(buffer);
- Atomics保证原子操作
Atomics.add(view, 0, 1);
- 利用事件循环优先级
Promise.resolve().then(() => console.log('微任务'));
setTimeout(() => console.log('宏任务'), 0);
- 异步迭代器处理流数据
async function* asyncGen() {
while (hasData) {
const data = await fetchChunk();
yield data;
}
}
for await (const chunk of asyncGen()) { ... }
- 取消异步任务
const controller = new AbortController();
fetch(url, { signal: controller.signal });
controller.abort();
- 防抖函数优化高频事件
function debounce(fn, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
- 节流函数限制执行频率
function throttle(fn, delay) {
let lastCall = 0;
return (...args) => {
const now = Date.now();
if (now - lastCall >= delay) {
fn(...args);
lastCall = now;
}
};
}
- 使用RxJS处理复杂异步流
import { fromEvent } from 'rxjs';
fromEvent(button, 'click')
.pipe(throttleTime(1000))
.subscribe(() => { ... });
- 利用async_hooks跟踪异步(Node.js)
const async_hooks = require('async_hooks');
const hook = async_hooks.createHook({
init(asyncId, type, triggerAsyncId) { ... }
});
hook.enable();
六、安全与防御性编程 (15例)
- XSS防御转义HTML
function escapeHTML(str) {
return str.replace(/[&<>"']/g, tag => ({
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
})[tag] || tag);
}
- 使用CSP防止内联脚本执行
<meta http-equiv="Content-Security-Policy" content="default-src 'self'">
- 禁用危险函数
window.eval = null;
- 验证用户输入格式
const isValidEmail = email => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
- 使用HTTPS保护传输数据
if (location.protocol !== 'https:') {
location.replace(`https://${location.host}${location.pathname}`);
}
- 设置HTTP安全头
app.use(helmet());
- 防范CSRF攻击
app.use(csurf());
- 限制资源加载来源
const script = document.createElement('script');
script.setAttribute('integrity', 'sha256-...');
script.setAttribute('crossorigin', 'anonymous');
- 使用JWT进行身份验证
fetch('/api', { headers: { Authorization: `Bearer ${token}` } });
- 防范点击劫持
if (self === top) {
document.documentElement.style.visibility = 'visible';
} else {
top.location = self.location;
}
- 使用CORS配置跨域
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', 'https://trusted.com');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
- 防范原型链污染
Object.freeze(Object.prototype);
- 使用沙箱运行不安全代码
const vm = require('vm');
const sandbox = { console };
vm.createContext(sandbox);
vm.runInContext('console.log("安全执行")', sandbox);
- 限制Cookie作用域
document.cookie = `token=abc123; Secure; SameSite=Strict; HttpOnly`;
- 使用子资源完整性校验
<script src="https://example.com/library.js"
integrity="sha384-..."
crossorigin="anonymous"></script>