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

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

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

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

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

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

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

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

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

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

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

合并對象:C0x28資訊網——每日最新資訊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()方法是你轉換數據的秘密武器:C0x28資訊網——每日最新資訊28at.com

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

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

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

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

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

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

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

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

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

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

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

使用 Promise.all() 來合并多個承諾并集體處理它們:C0x28資訊網——每日最新資訊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、動態屬性名稱:多功能對象鍵

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

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

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

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

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

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

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

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

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

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

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

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

正則表達式(RegExp)是用于模式匹配的強大工具:C0x28資訊網——每日最新資訊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:C0x28資訊網——每日最新資訊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():C0x28資訊網——每日最新資訊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簡化了處理異步請求:C0x28資訊網——每日最新資訊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、無拘無束的閉包:數據隱私

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

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

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

備忘錄化通過緩存函數結果來提高性能:C0x28資訊網——每日最新資訊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進行懶加載和滾動動畫:C0x28資訊網——每日最新資訊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模塊來編寫整潔、模塊化的代碼:C0x28資訊網——每日最新資訊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:超越對象

代理允許你攔截并自定義對象操作:C0x28資訊網——每日最新資訊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的小竅門和技巧,你已經有了足夠的裝備,可以將你的編程技能提升到新的水平。C0x28資訊網——每日最新資訊28at.com

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

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

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

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

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

標簽:
  • 熱門焦點
  • 鴻蒙OS 4.0公測機型公布:甚至連nova6都支持

    華為全新的HarmonyOS 4.0操作系統將于今天下午正式登場,官方在發布會之前也已經正式給出了可升級的機型產品,這意味著這些機型會率先支持升級享用。這次的HarmonyOS 4.0支持
  • 中興AX5400Pro+上手體驗:再升級 雙2.5G網口+USB 3.0這次全都有

    2021年11月的時候,中興先后發布了兩款路由器產品,中興AX5400和中興AX5400 Pro,從產品命名上就不難看出這是隸屬于同一系列的,但在外觀設計上這兩款產品可以說是完全沒一點關系
  • Raft算法:保障分布式系統共識的穩健之道

    1. 什么是Raft算法?Raft 是英文”Reliable、Replicated、Redundant、And Fault-Tolerant”(“可靠、可復制、可冗余、可容錯”)的首字母縮寫。Raft算法是一種用于在分布式系統
  • Flowable工作流引擎的科普與實踐

    一.引言當我們在日常工作和業務中需要進行各種審批流程時,可能會面臨一系列技術和業務上的挑戰。手動處理這些審批流程可能會導致開發成本的增加以及業務復雜度的上升。在這
  • JVM優化:實戰OutOfMemoryError異常

    一、Java堆溢出堆內存中主要存放對象、數組等,只要不斷地創建這些對象,并且保證 GC Roots 到對象之間有可達路徑來避免垃 圾收集回收機制清除這些對象,當這些對象所占空間超過
  • 東方甄選單飛:有些鳥注定是關不住的

    作者:彭寬鴻來源:華爾街科技眼&zwj;&zwj;&zwj;&zwj;&zwj;&zwj;&zwj;&zwj;&zwj;&zwj;東方甄選創始人俞敏洪帶隊的&ldquo;7天甘肅行&rdquo;直播活動已在近日順利收官。成立后一
  • iQOO 11S新品發布會

    iQOO將在7月4日19:00舉行新品發布會,推出杭州亞運會電競賽事官方用機iQOO 11S。
  • OPPO K11樣張首曝:千元機影像“卷”得真不錯!

    一直以來,OPPO K系列機型都保持著較為均衡的產品體驗,歷來都是2K價位的明星機型,去年推出的OPPO K10和OPPO K10 Pro兩款機型憑借各自的出色配置,堪稱有
  • 微軟發布Windows 11新版 引入全新任務欄狀態

    近日,微軟發布了Windows 11新版,而Build 22563更新主要引入了幾周前曝光的平板模式任務欄等,系統更流暢了。更新中,Windows 11加入了專門針對平板優化的任務欄
Top 主站蜘蛛池模板: 大港区| 寿光市| 邯郸县| 米林县| 宁安市| 密云县| 伊金霍洛旗| 四平市| 微博| 宜阳县| 金平| 綦江县| 天祝| 肇州县| 萨迦县| 清徐县| 绥芬河市| 南雄市| 南华县| 阿勒泰市| 固原市| 汾西县| 巴林右旗| 绥棱县| 宜春市| 博爱县| 桐柏县| 余江县| 常山县| 绥棱县| 临潭县| 湖北省| 阿尔山市| 榆林市| 阿巴嘎旗| 四会市| 五峰| 监利县| 楚雄市| 克什克腾旗| 闻喜县|