100个 JavaScript 黑客级神操作

一、类型与运算骚操作 (20例)

  1. 最短的空值检查
// 利用逻辑或快速取默认值
const name = inputName || 'Anonymous';
  1. 双重非位运算取整
~~3.14159; // 3 (等效Math.trunc)
  1. 异或交换变量
let a = 1, b = 2;
a ^= b; b ^= a; a ^= b; // a=2, b=1
  1. 利用空数组转数字0
+[]; // 0 (数组转字符串再转数字)
  1. 快速生成0-1随机布尔值
const bool = Math.random() >= 0.5; 
  1. 利用短路求值执行函数
condition && doSomething(); // condition为真时执行
  1. 逗号操作符返回最后一个值
let x = (1, 2, 3); // x = 3
  1. void 0 替代 undefined
const data = void 0; // 安全获取undefined
  1. 快速生成序列数组
Array.from({length:5}, (_,i) => i); // [0,1,2,3,4]
  1. 利用对象键名唯一性去重
const unique = [...new Set(arr)]; // Set去重
  1. 字符串转数组再反转
'hello'.split('').reverse().join(''); // 'olleh'
  1. 数字转字符串再转数组
String(123).split('').map(Number); // [1,2,3]
  1. 利用位运算判断奇偶
const isEven = num => (num & 1) === 0;
  1. 快速浮点数转整数
3.14 | 0; // 3 (直接截断)
  1. 利用指数运算符计算幂
2 ** 3; // 8 (替代Math.pow)
  1. 利用解构交换变量
[a, b] = [b, a]; // 无需临时变量
  1. 生成唯一递增ID
let id = 0; const getID = () => id++;
  1. 利用模板字符串调用函数
const greet = (strings, name) => `Hello ${name}`;
greet`World`; // "Hello World"
  1. 利用闭包缓存计算结果
const memoize = (fn) => { const cache = new Map(); return arg => cache.has(arg) ? cache.get(arg) : cache.set(arg, fn(arg)) && cache.get(arg); };
  1. 利用JSON进行深拷贝
const deepCopy = obj => JSON.parse(JSON.stringify(obj)); // 警告:无法处理函数和循环引用

二、函数与作用域黑魔法 (15例)

  1. 自执行匿名函数 (IIFE)
(() => { console.log('立即执行'); })();
  1. 函数柯里化
const add = a => b => a + b; add(2)(3); // 5
  1. 动态生成函数
const sum = new Function('a', 'b', 'return a + b');
  1. 绑定上下文到新对象
const bound = someFunc.bind({name: 'ctx'});
  1. 函数参数默认值
const greet = (name = 'Guest') => `Hello ${name}`;
  1. 剩余参数收集
const sum = (...nums) => nums.reduce((a,b) => a + b, 0);
  1. 函数属性模拟静态变量
function counter() { return ++counter.count || (counter.count = 0); }
  1. 利用闭包创建私有变量
function Person() { let age = 0; return { getAge: () => age, birthday: () => age++ };}
  1. 惰性函数定义(优化性能)
function lazyFunc() {
  lazyFunc = () => '优化后的逻辑'; // 覆盖自身
  return lazyFunc();
}
  1. 函数递归自身引用
const factorial = n => n <= 1 ? 1 : n * factorial(n - 1);
  1. 利用arguments转数组
function logArgs() { console.log([...arguments]); }
  1. 闭包陷阱(循环变量问题)
for (var i = 0; i < 3; i++) { 
  setTimeout(() => console.log(i), 100); // 输出3次3 
}
  1. 解决闭包陷阱的IIFE方案
for (var i = 0; i < 3; i++) { 
  (function(j) { setTimeout(() => console.log(j), 100); })(i);
}
  1. 箭头函数绑定词法作用域
const obj = {
  value: 42,
  getValue: () => this.value // 箭头函数无this绑定,输出undefined
};
  1. 利用Proxy拦截函数调用
const handler = { apply: (target, thisArg, args) => { console.log('函数被调用'); return target(...args); } };
const proxiedFunc = new Proxy(() => {}, handler);

三、对象与原型链技巧 (15例)

  1. 对象属性名动态计算
const key = 'name';
const obj = { [key]: 'Alice' }; // {name: 'Alice'}
  1. 合并对象(浅层)
const merged = { ...obj1, ...obj2 };
  1. 对象冻结防止修改
const frozen = Object.freeze({ value: 42 });
  1. 检测对象是否为空
const isEmpty = obj => Object.keys(obj).length === 0;
  1. 对象迭代键值对
for (const [key, value] of Object.entries(obj)) { ... }
  1. 利用原型链实现继承
function Parent() {}
function Child() {}
Child.prototype = Object.create(Parent.prototype);
  1. 修改原型链添加方法(慎用!)
Array.prototype.last = function() { return this[this.length-1]; };
[1,2,3].last(); // 3 (污染原型链)
  1. 利用Object.defineProperty定义属性
const obj = {};
Object.defineProperty(obj, 'readOnlyProp', { value: 42, writable: false });
  1. 检测属性存在性
'toString' in {}; // true (原型链属性)
obj.hasOwnProperty('key'); // 仅检测自身属性
  1. 利用Symbol作为唯一键
const privateKey = Symbol('internal');
const obj = { [privateKey]: 'secret' };
  1. 使用WeakMap存储私有数据
const privates = new WeakMap();
function MyClass() { privates.set(this, { data: 42 }); }
MyClass.prototype.getData = function() { return privates.get(this).data; };
  1. 对象解构别名
const { name: userName, age } = { name: 'Alice', age: 30 };
  1. 对象属性简写
const name = 'Alice';
const user = { name }; // { name: 'Alice' }
  1. 链式判断运算符
const street = user?.address?.street; // 避免Cannot read property错误
  1. 可选链调用函数
obj.someMethod?.(); // 方法存在时调用

四、浏览器API骚操作 (20例)

  1. 拦截XHR请求
const originalXHR = window.XMLHttpRequest;
window.XMLHttpRequest = class extends originalXHR {
  open(...args) { console.log('请求:', args); super.open(...args); }
};
  1. 监听所有点击事件
document.addEventListener('click', e => console.log('点击:', e.target));
  1. 使用事件委托优化性能
document.querySelector('#list').addEventListener('click', e => {
  if (e.target.matches('li.item')) { console.log('Item被点击'); }
});
  1. 动态加载脚本
const script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery.min.js';
document.head.appendChild(script);
  1. 快速清空DOM节点
element.innerHTML = '';
// 或
while (element.firstChild) element.removeChild(element.firstChild);
  1. 使用文档片段批量插入
const fragment = document.createDocumentFragment();
items.forEach(item => fragment.appendChild(createElement(item)));
container.appendChild(fragment);
  1. 获取元素计算样式
const style = window.getComputedStyle(element);
const width = style.getPropertyValue('width');
  1. 监听CSS动画结束
element.addEventListener('animationend', () => { ... });
  1. 全屏API控制
document.documentElement.requestFullscreen();
document.exitFullscreen();
  1. 获取用户剪贴板数据
navigator.clipboard.readText().then(text => console.log(text));
  1. 写入剪贴板
navigator.clipboard.writeText('要复制的文本');
  1. 监听页面可见性变化
document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'visible') { ... }
});
  1. 使用Geolocation获取位置
navigator.geolocation.getCurrentPosition(pos => {
  const { latitude, longitude } = pos.coords;
});
  1. 使用WebSocket实时通信
const socket = new WebSocket('ws://example.com');
socket.onmessage = event => { console.log('收到消息:', event.data); };
  1. 使用Fetch发起请求
fetch('/api/data')
  .then(res => res.json())
  .then(data => console.log(data));
  1. 使用AbortController取消请求
const controller = new AbortController();
fetch(url, { signal: controller.signal });
controller.abort(); // 取消请求
  1. 使用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));
  1. 使用MutationObserver监听DOM变化
const observer = new MutationObserver(mutations => {
  mutations.forEach(mutation => { ... });
});
observer.observe(targetNode, { childList: true, subtree: true });
  1. 使用Performance API测量性能
performance.mark('start');
// ...执行代码
performance.mark('end');
performance.measure('耗时', 'start', 'end');
const duration = performance.getEntriesByName('耗时')[0].duration;
  1. 使用Canvas绘制图像
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 100, 100);

五、异步与并发黑科技 (15例)

  1. Promise链式调用
fetchData()
  .then(processData)
  .then(data => saveData(data))
  .catch(handleError);
  1. 并行执行多个Promise
Promise.all([promise1, promise2]).then(([res1, res2]) => { ... });
  1. Promise超时处理
const timeout = (ms) => new Promise((_, reject) => 
  setTimeout(() => reject(new Error('超时')), ms)
);
Promise.race([fetchData(), timeout(5000)]);
  1. Async/Await简化异步
async function loadData() {
  try {
    const data = await fetchData();
    const processed = await processData(data);
    return processed;
  } catch (error) {
    handleError(error);
  }
}
  1. 生成器函数处理异步流程
function* asyncGenerator() {
  const data = yield fetchData();
  const result = yield processData(data);
  return result;
}
// 需要外部执行器驱动
  1. 使用Web Workers多线程
const worker = new Worker('worker.js');
worker.postMessage(data);
worker.onmessage = e => console.log(e.data);
  1. SharedArrayBuffer多线程共享内存
const buffer = new SharedArrayBuffer(16);
const view = new Int32Array(buffer);
// 主线程与Worker共享buffer
  1. Atomics保证原子操作
Atomics.add(view, 0, 1); // 原子加法
  1. 利用事件循环优先级
// 微任务优先于宏任务
Promise.resolve().then(() => console.log('微任务'));
setTimeout(() => console.log('宏任务'), 0);
  1. 异步迭代器处理流数据
async function* asyncGen() {
  while (hasData) {
    const data = await fetchChunk();
    yield data;
  }
}
for await (const chunk of asyncGen()) { ... }
  1. 取消异步任务
const controller = new AbortController();
fetch(url, { signal: controller.signal });
controller.abort(); // 取消请求
  1. 防抖函数优化高频事件
function debounce(fn, delay) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}
  1. 节流函数限制执行频率
function throttle(fn, delay) {
  let lastCall = 0;
  return (...args) => {
    const now = Date.now();
    if (now - lastCall >= delay) {
      fn(...args);
      lastCall = now;
    }
  };
}
  1. 使用RxJS处理复杂异步流
import { fromEvent } from 'rxjs';
fromEvent(button, 'click')
  .pipe(throttleTime(1000))
  .subscribe(() => { ... });
  1. 利用async_hooks跟踪异步(Node.js)
const async_hooks = require('async_hooks');
const hook = async_hooks.createHook({ 
  init(asyncId, type, triggerAsyncId) { ... }
});
hook.enable();

六、安全与防御性编程 (15例)

  1. XSS防御转义HTML
function escapeHTML(str) {
  return str.replace(/[&<>"']/g, tag => ({
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#39;'
  })[tag] || tag);
}
  1. 使用CSP防止内联脚本执行
<meta http-equiv="Content-Security-Policy" content="default-src 'self'">
  1. 禁用危险函数
window.eval = null; // 禁用eval
  1. 验证用户输入格式
const isValidEmail = email => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  1. 使用HTTPS保护传输数据
if (location.protocol !== 'https:') {
  location.replace(`https://${location.host}${location.pathname}`);
}
  1. 设置HTTP安全头
// 后端设置(示例为Express)
app.use(helmet()); // 使用helmet中间件
  1. 防范CSRF攻击
// 后端生成并验证CSRF Token
app.use(csurf());
  1. 限制资源加载来源
const script = document.createElement('script');
script.setAttribute('integrity', 'sha256-...');
script.setAttribute('crossorigin', 'anonymous');
  1. 使用JWT进行身份验证
// 发送请求时携带Token
fetch('/api', { headers: { Authorization: `Bearer ${token}` } });
  1. 防范点击劫持
if (self === top) { 
  document.documentElement.style.visibility = 'visible';
} else { 
  top.location = self.location; 
}
  1. 使用CORS配置跨域
// 后端设置(Express示例)
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', 'https://trusted.com');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});
  1. 防范原型链污染
Object.freeze(Object.prototype); // 冻结原型链
  1. 使用沙箱运行不安全代码
// Node.js中使用vm模块
const vm = require('vm');
const sandbox = { console };
vm.createContext(sandbox);
vm.runInContext('console.log("安全执行")', sandbox);
  1. 限制Cookie作用域
document.cookie = `token=abc123; Secure; SameSite=Strict; HttpOnly`;
  1. 使用子资源完整性校验
<script src="https://example.com/library.js" 
        integrity="sha384-..." 
        crossorigin="anonymous"></script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值