解構(gòu)允許你輕松地從數(shù)組或?qū)ο笾薪獍?。以下是一個例子:
const person = { name: 'Alice’, age: 30 };const { name, age } = person;console.log(name); // Output: Aliceconsole.log(age); // Output: 30
擴展運算符(...)讓你能輕松地創(chuàng)建數(shù)組的副本并合并對象:
const originalArray = [1, 2, 3];const clonedArray = [...originalArray];console.log(clonedArray); // Output: [1, 2, 3]
合并對象:
const obj1 = { a: 1, b: 2 };const obj2 = { b: 3, c: 4 };const merged = { ...obj1, ...obj2 };console.log(merged); // Output: { a: 1, b: 3, c: 4 }
map()方法是你轉(zhuǎn)換數(shù)據(jù)的秘密武器:
const numbers = [1, 2, 3];const squared = numbers.map(num => num * num);console.log(squared); // Output: [1, 4, 9]
使用 && 和 || 來創(chuàng)建清晰簡潔的條件語句:
const name = user.name || 'Guest';console.log(name); // Output: Guest
將setTimeout()鏈接起來可以創(chuàng)建一系列的延遲操作:
function delayedLog(message, time) { setTimeout(() => { console.log(message); }, time);}delayedLog('Hello', 1000); // Output (after 1 second): Hello
箭頭函數(shù)(() => {})不僅簡潔,而且還保留了this的值:
const greet = name => `Hello, ${name}!`;console.log(greet(’Alice’)); // Output: Hello, Alice!
使用 Promise.all() 來合并多個承諾并集體處理它們:
const promise1 = fetch('url1');const promise2 = fetch('url2');Promise.all([promise1, promise2]) .then(responses => console.log(responses)) .catch(error => console.error(error));
可以使用方括號將變量用作對象屬性名稱:
const key = 'name';const person = { [key]: 'Alice' };console.log(person.name); // Output: Alice
模板字面量 (${}) 允許你在字符串中嵌入表達式:
const name = 'Alice';const greeting = `Hello, ${name}!`;console.log(greeting); // Output: Hello, Alice!
使用 Number.isNaN() 來準確地檢查一個值是否為 NaN:
const notANumber = 'Not a number';console.log(Number.isNaN(notANumber)); // Output: false
在處理嵌套屬性時,通過可選鏈來避免錯誤:
const user = { info: { name: 'Alice' } };console.log(user.info?.age); // Output: undefined
正則表達式(RegExp)是用于模式匹配的強大工具:
const text = 'Hello, world!';const pattern = /Hello/g;console.log(text.match(pattern)); // Output: ['Hello']
在JSON.parse()中的reviver參數(shù)允許你轉(zhuǎn)換解析后的JSON:
const data = '{"age":"30"}';const parsed = JSON.parse(data, (key, value) => { if (key === 'age') return Number(value); return value;});console.log(parsed.age); // Output: 30
使用console.table()和console.groupCollapsed()超越console.log():
const users = [{ name: 'Alice' }, { name: 'Bob' }];console.table(users);console.groupCollapsed(’Details’);console.log(’Name: Alice’);console.log(’Age: 30’);console.groupEnd();
使用fetch()的async/await簡化了處理異步請求:
async function fetchData() { try { const response = await fetch('url'); const data = await response.json(); console.log(data); } catch (error) { console.error(error); }}fetchData();
閉包讓你在函數(shù)中創(chuàng)建私有變量:
function createCounter() { let count = 0; return function () { count++; console.log(count); };}const counter = createCounter();counter(); // Output: 1counter(); // Output: 2
備忘錄化通過緩存函數(shù)結(jié)果來提高性能:
function fibonacci(n, memo = {}) { if (n in memo) return memo[n]; if (n <= 2) return 1; memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo); return memo[n];}console.log(fibonacci(10)); // Output: 55
使用 Intersection Observer 者API進行懶加載和滾動動畫:
const observer = new IntersectionObserver(entries => { entries.forEach(entry => { if (entry.isIntersecting) { entry.target.classList.add('fade-in'); observer.unobserve(entry.target); } });});const elements = document.querySelectorAll('.animate');elements.forEach(element => observer.observe(element));
使用ES6模塊來編寫整潔、模塊化的代碼:
// math.jsexport function add(a, b) { return a + b;}// app.jsimport { add } from './math.js';console.log(add(2, 3)); // Output: 5
代理允許你攔截并自定義對象操作:
const handler = { get(target, prop) { return `Property "${prop}" doesn't exist.`; }};const proxy = new Proxy({}, handler);console.log(proxy.name); // Output: Property "name" doesn’t exist.
配備了這20個JavaScript的小竅門和技巧,你已經(jīng)有了足夠的裝備,可以將你的編程技能提升到新的水平。
本文鏈接:http://www.tebozhan.com/showinfo-26-14010-0.html現(xiàn)在就可以使用的 20 個 JavaScript 技巧和竅門
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。郵件:2376512515@qq.com