日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

當前位置:首頁 > 科技  > 軟件

現在就可以使用的 20 個 JavaScript 技巧和竅門

來源: 責編: 時間:2023-10-18 17:59:17 290觀看
導讀1、解構魔法:輕松提取值解構允許你輕松地從數組或對象中解包值。以下是一個例子:const person = { name: 'Alice’, age: 30 };const { name, age } = person;console.log(name); // Output: Aliceconsole.log(age); //

bMg28資訊網——每日最新資訊28at.com

1、解構魔法:輕松提取值

解構允許你輕松地從數組或對象中解包值。以下是一個例子:bMg28資訊網——每日最新資訊28at.com

const person = { name: 'Alice’, age: 30 };const { name, age } = person;console.log(name); // Output: Aliceconsole.log(age); // Output: 30

2、展開運算:克隆數組和合并對象

擴展運算符(...)讓你能輕松地創建數組的副本并合并對象:bMg28資訊網——每日最新資訊28at.com

const originalArray = [1, 2, 3];const clonedArray = [...originalArray];console.log(clonedArray); // Output: [1, 2, 3]

合并對象:bMg28資訊網——每日最新資訊28at.com

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() 輕松實現轉換

map()方法是你轉換數據的秘密武器:bMg28資訊網——每日最新資訊28at.com

const numbers = [1, 2, 3];const squared = numbers.map(num => num * num);console.log(squared); // Output: [1, 4, 9]

4、 && 和 || 的短路操作:優雅的條件判斷

使用 && 和 || 來創建清晰簡潔的條件語句:bMg28資訊網——每日最新資訊28at.com

const name = user.name || 'Guest';console.log(name); // Output: Guest

5、串聯 setTimeout():延遲序列化

將setTimeout()鏈接起來可以創建一系列的延遲操作:bMg28資訊網——每日最新資訊28at.com

function delayedLog(message, time) {  setTimeout(() => {    console.log(message);  }, time);}delayedLog('Hello', 1000); // Output (after 1 second): Hello

6、箭頭函數:簡潔而強大

箭頭函數(() => {})不僅簡潔,而且還保留了this的值:bMg28資訊網——每日最新資訊28at.com

const greet = name => `Hello, ${name}!`;console.log(greet(’Alice’)); // Output: Hello, Alice!

7、掌握 Promise.all():處理多個 Promise

使用 Promise.all() 來合并多個承諾并集體處理它們:bMg28資訊網——每日最新資訊28at.com

const promise1 = fetch('url1');const promise2 = fetch('url2');Promise.all([promise1, promise2])  .then(responses => console.log(responses))  .catch(error => console.error(error));

8、動態屬性名稱:多功能對象鍵

可以使用方括號將變量用作對象屬性名稱:bMg28資訊網——每日最新資訊28at.com

const key = 'name';const person = { [key]: 'Alice' };console.log(person.name); // Output: Alice

9、模板字面量魔法:字符串格式化

模板字面量 (${}) 允許你在字符串中嵌入表達式:bMg28資訊網——每日最新資訊28at.com

const name = 'Alice';const greeting = `Hello, ${name}!`;console.log(greeting); // Output: Hello, Alice!

10、NaN 檢查:更安全的替代方案

使用 Number.isNaN() 來準確地檢查一個值是否為 NaN:bMg28資訊網——每日最新資訊28at.com

const notANumber = 'Not a number';console.log(Number.isNaN(notANumber)); // Output: false

11、可選鏈(?.):馴服未定義的值

在處理嵌套屬性時,通過可選鏈來避免錯誤:bMg28資訊網——每日最新資訊28at.com

const user = { info: { name: 'Alice' } };console.log(user.info?.age); // Output: undefined

12、正則表達式復興:掌握模式

正則表達式(RegExp)是用于模式匹配的強大工具:bMg28資訊網——每日最新資訊28at.com

const text = 'Hello, world!';const pattern = /Hello/g;console.log(text.match(pattern)); // Output: ['Hello']

13、JSON.parse() reviver:轉換解析數據

在JSON.parse()中的reviver參數允許你轉換解析后的JSON:bMg28資訊網——每日最新資訊28at.com

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. 酷炫控制臺技巧:調試的樂趣

使用console.table()和console.groupCollapsed()超越console.log():bMg28資訊網——每日最新資訊28at.com

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獲取:異步簡易性

使用fetch()的async/await簡化了處理異步請求:bMg28資訊網——每日最新資訊28at.com

async function fetchData() {  try {    const response = await fetch('url');    const data = await response.json();    console.log(data);  } catch (error) {    console.error(error);  }}fetchData();

16、無拘無束的閉包:數據隱私

閉包讓你在函數中創建私有變量:bMg28資訊網——每日最新資訊28at.com

function createCounter() {  let count = 0;  return function () {    count++;    console.log(count);  };}const counter = createCounter();counter(); // Output: 1counter(); // Output: 2

17、提高速度的緩存:高效重新計算

備忘錄化通過緩存函數結果來提高性能:bMg28資訊網——每日最新資訊28at.com

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進行懶加載和滾動動畫:bMg28資訊網——每日最新資訊28at.com

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模塊來編寫整潔、模塊化的代碼:bMg28資訊網——每日最新資訊28at.com

// math.jsexport function add(a, b) {  return a + b;}// app.jsimport { add } from './math.js';console.log(add(2, 3)); // Output: 5

20、Proxy:超越對象

代理允許你攔截并自定義對象操作:bMg28資訊網——每日最新資訊28at.com

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的小竅門和技巧,你已經有了足夠的裝備,可以將你的編程技能提升到新的水平。bMg28資訊網——每日最新資訊28at.com

bMg28資訊網——每日最新資訊28at.com

本文鏈接:http://www.www897cc.com/showinfo-26-14010-0.html現在就可以使用的 20 個 JavaScript 技巧和竅門

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 為什么架構設計總沒法一勞永逸?

下一篇: Node.js 21 正式發布,趕緊來看看有哪些更新吧!

標簽:
  • 熱門焦點
Top 主站蜘蛛池模板: 广灵县| 耒阳市| 西丰县| 资阳市| 墨江| 巴中市| 拉孜县| 林口县| 泰安市| 天气| 汉寿县| 汉源县| 绥化市| 京山县| 元朗区| 如皋市| 灌南县| 蕲春县| 汉中市| 法库县| 苍溪县| 聂荣县| 西充县| 马山县| 化州市| 新安县| 准格尔旗| 高青县| 寻乌县| 青浦区| 丰镇市| 哈巴河县| 永嘉县| 甘泉县| 新余市| 平泉县| 镇坪县| 呼玛县| 浏阳市| 尚义县| 兰西县|