1.Intersection Observer:
const callback = (entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
console.log('Element is in the viewport!');
}
});
};
const options = {
root: null, // use the viewport as the root
threshold: 0.5 // trigger when 50% of the element is visible
};
const observer = new IntersectionObserver(callback, options);
observer.observe(myElement);
2.Promise 和 异步/await:
function fetchData() {
return new Promise(resolve => {
// 异步操作
resolve(data);
});
}
async function fetchDataAsync() {
const data = await fetchData();
console.log(data);
}
3.Map 和 Set 数据结构:
const myMap = new Map();
myMap.set('key', 'value');
const mySet = new Set([1, 2, 3, 4, 5]);
4.Proxy 和 Reflect:
const handler = {
get(target, prop) {
console.log(`Getting property ${prop}`);
return target[prop];
}
};
const proxy = new Proxy(myObject, handler);
5.函数柯里化 (Function Currying):
const curry = fn => (...args) =>
args.length >= fn.length ? fn(...args) : curry(fn.bind(null, ...args));
const add = (a, b, c) => a + b + c;
const curriedAdd = curry(add);
6.Generator 函数:
function* generateSequence() {
yield 1;
yield 2;
yield 3;
}
const myGenerator = generateSequence();
console.log(myGenerator.next().value); // 1
7.WeakMap 和 WeakSet:
const myWeakMap = new WeakMap();
const keyObject = {};
myWeakMap.set(keyObject, 'value');
8.扩展运算符和剩余参数 (Spread Operator and Rest Parameters):
const newArray = [...oldArray, newValue];
function sum(...args) { return args.reduce((acc, val) => acc + val, 0); }
9.Web Workers:
// In main.js
const worker = new Worker('worker.js');
worker.postMessage('Hello from main.js!');
// In worker.js
onmessage = event => {
console.log('Message received in worker.js:', event.data);
};
10.异步迭代器:
const fetchData = async () => {
const response = await fetch('https://api.example.com/data');
const dataStream = response.body.getReader();
while (true) {
const { done, value } = await dataStream.read();
if (done) break;
console.log(value);
}
};
fetchData();
11.Object.freeze():
const myObject = { prop1: 'value1', prop2: 'value2' };
const frozenObject = Object.freeze(myObject);
// 试图修改将在严格模式下导致错误
frozenObject.prop1 = 'new value';
12.记忆化:
const memoize = (func) => {
const cache = {};
return (...args) => {
const key = JSON.stringify(args);
if (cache[key]) {
return cache[key];
} else {
const result = func(...args);
cache[key] = result;
return result;
}
};
};
const expensiveCalculation = memoize((n) => {
console.log('进行昂贵的计算...');
return n * 2;
});
console.log(expensiveCalculation(5)); // 执行计算
console.log(expensiveCalculation(5)); // 返回缓存的结果
13.自定义事件:
const eventEmitter = new EventTarget();
const handleCustomEvent = (event) => {
console.log(`触发自定义事件:${event.detail}`);
};
eventEmitter.addEventListener('customEvent', handleCustomEvent);
eventEmitter.dispatchEvent(new CustomEvent('customEvent', { detail: '传递的数据' }));
14.代理验证:
const validator = (target, prop, value) => {
if (prop === 'age' && (typeof value !== 'number' || value < 0)) {
throw new Error('无效的年龄值');
}
target[prop] = value;
return true;
};
const person = new Proxy({}, { set: validator });
person.age = 25; // 有效
person.age = -5; // 抛出错误
15.Object.fromEntries():
const keyValueArray = [['key1', 'value1'], ['key2', 'value2']];
const myObject = Object.fromEntries(keyValueArray);
console.log(myObject); // { key1: 'value1', key2: 'value2' }
16.AbortController 和 AbortSignal:
const controller = new AbortController();
const signal = controller.signal;
fetch('https://api.example.com/data', { signal })
.then(response => response.json())
.then(data => console.log(data))
.catch(error => {
if (error.name === 'AbortError') {
console.log('Request was aborted');
} else {
console.error(error);
}
});
// 取消请求
controller.abort();
17.Blob 和 URL.createObjectURL():
const textContent = 'Hello, Blob!';
const blob = new Blob([textContent], { type: 'text/plain' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'example.txt';
link.click();
18.IndexedDB:
const request = indexedDB.open('myDatabase', 1);
request.onupgradeneeded = event => {
const db = event.target.result;
const objectStore = db.createObjectStore('myObjectStore', { keyPath: 'id' });
};
request.onsuccess = event => {
const db = event.target.result;
const transaction = db.transaction('myObjectStore', 'readwrite');
const objectStore = transaction.objectStore('myObjectStore');
objectStore.add({ id: 1, data: 'example' });
};
19.Speech Recognition API:
const recognition = new SpeechRecognition();
recognition.lang = 'en-US';
recognition.onresult = event => {
const transcript = event.results[0][0].transcript;
console.log(`User said: ${transcript}`);
};
recognition.start();
20.Resize Observer:
const observer = new ResizeObserver(entries => {
entries.forEach(entry => {
console.log(`Element size changed to ${entry.contentRect.width}x${entry.contentRect.height}`);
});
});
const targetElement = document.getElementById('resizeMe');
observer.observe(targetElement);