20個拿來就能用的JavaScript技巧分享
1. 解構(gòu)魔法:輕松提取值
解構(gòu)允許你輕松地從數(shù)組或?qū)ο笾薪獍怠R韵率且粋€例子:
const person = { name: 'Alice', age: 30 }; const { name, age } = person; console.log(name); // Output: Alice console.log(age); // Output: 30
2. 展開運算:克隆數(shù)組和合并對象
擴展運算符(...
)讓你能輕松地創(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 }
3. map() 輕松實現(xiàn)轉(zhuǎn)換
map()
方法是你轉(zhuǎn)換數(shù)據(jù)的秘密武器:
const numbers = [1, 2, 3]; const squared = numbers.map(num => num * num); console.log(squared); // Output: [1, 4, 9]
4. 使用 && 和 || 的短路操作:優(yōu)雅的條件判斷
使用 &&
和 ||
來創(chuàng)建清晰簡潔的條件語句:
const name = user.name || 'Guest'; console.log(name); // Output: Guest
5.串聯(lián) setTimeout():延遲序列化
將setTimeout()
鏈接起來可以創(chuàng)建一系列的延遲操作:
function delayedLog(message, time) { setTimeout(() => { console.log(message); }, time); } delayedLog('Hello', 1000); // Output (after 1 second): Hello
6. 箭頭函數(shù):簡潔而強大
箭頭函數(shù)(() => {}
)不僅簡潔,而且還保留了this
的值:
const greet = name => `Hello, ${name}!`; console.log(greet('Alice')); // Output: Hello, Alice!
7. 掌握 Promise.all():處理多個 Promise
使用 Promise.all()
來合并多個承諾并集體處理它們:
const promise1 = fetch('url1'); const promise2 = fetch('url2'); Promise.all([promise1, promise2]) .then(responses => console.log(responses)) .catch(error => console.error(error));
8. 動態(tài)屬性名稱:多功能對象鍵
可以使用方括號將變量用作對象屬性名稱:
const key = 'name'; const person = { [key]: 'Alice' }; console.log(person.name); // Output: Alice
9. 模板字面量魔法:字符串格式化
模板字面量 (${}
) 允許你在字符串中嵌入表達(dá)式:
const name = 'Alice'; const greeting = `Hello, ${name}!`; console.log(greeting); // Output: Hello, Alice!
10. NaN 檢查:更安全的替代方案
使用 Number.isNaN()
來準(zhǔn)確地檢查一個值是否為 NaN:
const notANumber = 'Not a number'; console.log(Number.isNaN(notANumber)); // Output: false
11. 可選鏈(?.):馴服未定義的值
在處理嵌套屬性時,通過可選鏈來避免錯誤:
const user = { info: { name: 'Alice' } }; console.log(user.info?.age); // Output: undefined
12. 正則表達(dá)式復(fù)興:掌握模式
正則表達(dá)式(RegExp
)是用于模式匹配的強大工具:
const text = 'Hello, world!'; const pattern = /Hello/g; console.log(text.match(pattern)); // Output: ['Hello']
13. JSON.parse() reviver:轉(zhuǎn)換解析數(shù)據(jù)
在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
14. 酷炫控制臺技巧:調(diào)試的樂趣
使用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();
15. 使用async/await獲?。寒惒胶喴仔?/h2>
使用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();
16. 無拘無束的閉包:數(shù)據(jù)隱私
閉包讓你在函數(shù)中創(chuàng)建私有變量:
function createCounter() { let count = 0; return function () { count++; console.log(count); }; } const counter = createCounter(); counter(); // Output: 1 counter(); // Output: 2
17. 提高速度的緩存:高效重新計算
備忘錄化通過緩存函數(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
18. IntersectionObserver:輕松的滾動效果
使用 Intersection Observer 者API進(jìn)行懶加載和滾動動畫:
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));
19. 清晰代碼的ES6模塊:有組織且模塊化
使用ES6模塊來編寫整潔、模塊化的代碼:
// math.js export function add(a, b) { return a + b; } // app.js import { add } from './math.js'; console.log(add(2, 3)); // Output: 5
20. Proxy:超越對象
代理允許你攔截并自定義對象操作:
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)有了足夠的裝備,可以將你的編程技能提升到新的水平。
以上就是20個拿來就能用的JavaScript技巧分享的詳細(xì)內(nèi)容,更多關(guān)于JavaScript技巧的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
jquery插件bootstrapValidator數(shù)據(jù)驗證詳解
這篇文章主要為大家詳細(xì)介紹了jquery插件bootstrapValidator數(shù)據(jù)驗證使用教程,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-11-11JavaScript實現(xiàn)仿新浪微博大廳和騰訊微博首頁滾動特效源碼
最近看到朋友用JavaScript實現(xiàn)仿新浪微博大廳和未登錄騰訊微博首頁滾動效果,朋友使用jquery實現(xiàn)的,在網(wǎng)上看到有用js制作的也比較好,于是把我的內(nèi)容整理分享給大家,具體詳解請看本文2015-09-09javascript動態(tài)添加、修改、刪除對象的屬性與方法詳解
本篇文章主要是對javascript動態(tài)添加、修改、刪除對象的屬性與方法進(jìn)行了介紹,需要的朋友可以過來參考下,希望對大家有所幫助2014-01-01