🔍 搜尋結果:sre

🔍 搜尋結果:sre

useReducer() 優於 useState() 的 3 個理由

這是什麼 ---- `useReducer()`是 React Hooks API 中的一個方法,與`useState`類似,但為您提供了更多控制權來管理狀態。它接受一個reducer函數和初始狀態作為參數,並傳回狀態和調度方法: ``` const [state, dispatch] = React.useReducer(reducerFn, initialState, initFn); ``` reducer(之所以這樣稱呼,是因為您將傳遞給陣列方法`Array.prototype.reduce(reducer, initialValue)`函數類型)是取自 Redux 的模式。如果您不熟悉 Redux,簡而言之,reducer 是一個純函數,它將先前的狀態和操作作為參數,並傳回下一個狀態。 ``` (prevState, action) => newState ``` 操作是描述發生的事情的一條訊息,並且根據該訊息,reducer 指定狀態應如何變更。動作透過`dispatch(action)`方法傳遞。 使用它的 3 個理由 ---------- 大多數時候,您只需使用`useState()`方法就可以了,該方法建立在`useReducer()`之上。但有些情況下`useReducer()`較可取。 ### 下一個狀態取決於上一個狀態 當狀態依賴前一個方法時,使用此方法總是更好。它會給你一個更可預測的狀態轉換。簡單的例子是: ``` function reducer(state, action) { switch (action.type) { case 'ADD': return { count: state.count + 1 }; case 'SUB': return { count: state.count - 1 }; default: return state; } } function Counter() { const [state, dispatch] = React.useReducer(reducer, { count: 0 }); return ( <> Count: {state.count} <button onClick={() => dispatch({type: 'ADD'})}>Add</button> <button onClick={() => dispatch({type: 'SUB'})}>Substract</button> </> ); } ``` ### 複雜狀態形狀 當狀態包含多個原始值時,例如巢狀物件或陣列。例如: ``` const [state, dispatch] = React.useReducer( fetchUsersReducer, { users: [ { name: 'John', subscribred: false }, { name: 'Jane', subscribred: true }, ], loading: false, error: false, }, ); ``` 管理這種本地狀態更容易,因為參數相互依賴,並且所有邏輯都可以封裝到一個reducer中。 ### 易於測試 reducer是純函數,這意味著它們沒有副作用,並且在給定相同參數的情況下必須返回相同的結果。測試它們更容易,因為它們不依賴 React。讓我們從計數器範例中取得一個reducer並使用模擬狀態對其進行測試: ``` test("increments the count by one", () => { const newState = reducer({ count: 0 }, { type: "ADD" }); expect(newState.count).toBe(1) }) ``` 結論 -- `useReducer()`是`useState()`的替代方法,它使您可以更好地控制狀態管理並使測試更容易。所有情況都可以使用`useState()`方法來完成,因此總而言之,使用您熟悉的方法,並且對您和同事來說更容易理解。 --- 原文出處:https://dev.to/spukas/3-reasons-to-usereducer-over-usestate-43ad

我如何建立 NotesGPT – 一個全端人工智慧語音筆記應用程式

上週,我推出了[notesGPT](https://usenotesgpt.com/) ,這是一款免費開源語音記事應用程式,上週迄今為止已有[35,000 名訪客](https://twitter.com/nutlope/status/1760053364791050285)、7,000 名用戶和超過 1,000 名 GitHub star。它允許您錄製語音筆記,使用[Whisper](https://github.com/openai/whisper)進行轉錄,並透過[Together](https://together.ai/)使用 Mixtral 來提取操作項並將其顯示在操作項視圖中。它也是[完全開源的](https://github.com/nutlope/notesgpt),配備了身份驗證、儲存、向量搜尋、操作項,並且在行動裝置上完全響應,易於使用。 我將向您詳細介紹我是如何建造它的。 架構和技術堆疊 ------- 這是架構的快速圖表。我們將更深入地討論每個部分,並同時展示程式碼範例。 ![架構圖](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sjl3i4bu23fn0pabldsw.png) 這是我使用的整體技術堆疊: - 資料庫和雲端函數的[convex](https://convex.dev/) - Next.js [App Router](https://nextjs.org/docs/app)框架 - [複製](https://replicate.com/)Whisper 轉錄 - LLM 與[JSON 模式](https://docs.together.ai/docs/json-mode)的[Mixtral](https://mistral.ai/news/mixtral-of-experts/) - [Together.ai](http://Together.ai)用於推理和嵌入 - 用於儲存語音註釋的[凸檔存儲](https://docs.convex.dev/file-storage) - [凸向量搜尋](https://docs.convex.dev/vector-search)用於向量搜尋 - 負責使用者身份驗證的[職員](https://clerk.dev/) - [Tailwind CSS](https://tailwindcss.com/)樣式 登陸頁面 ---- 該應用程式的第一部分是您導航到notesGPT 時看到的登入頁面。 ![NotesGPT 的登陸頁面](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0hfscmudh4l33oab3azw.png) 用戶首先看到的是這個登陸頁面,它與應用程式的其餘部分一起使用 Next.js 和 Tailwind CSS 進行樣式建立。我喜歡使用 Next.js,因為它可以輕鬆啟動 Web 應用程式並編寫 React 程式碼。 Tailwind CSS 也很棒,因為它允許您在網頁上快速迭代,同時與 JSX 保持在同一檔案中。 與 Clerk 和 Convex 進行身份驗證 ----------------------- 當使用者點擊主頁上的任一按鈕時,他們將被導向到登入畫面。這是由 Clerk 提供支援的,這是一個與 Convex 很好整合的簡單身份驗證解決方案,我們將在整個後端使用它,包括雲端功能、資料庫、儲存和向量搜尋。 ![認證頁面](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/02khgd6f2jfew1w7dufn.png) Clerk 和 Convex 都很容易設定。您只需在這兩個服務上建立一個帳戶,安裝它們的 npm 庫,執行`npx convex dev`來設定您的凸資料夾,然後建立一個如下所示的`ConvexProvider.ts`檔案來包裝您的應用程式。 ``` 'use client'; import { ReactNode } from 'react'; import { ConvexReactClient } from 'convex/react'; import { ConvexProviderWithClerk } from 'convex/react-clerk'; import { ClerkProvider, useAuth } from '@clerk/nextjs'; const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL!); export default function ConvexClientProvider({ children, }: { children: ReactNode; }) { return ( <ClerkProvider publishableKey={process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY!} > <ConvexProviderWithClerk client={convex} useAuth={useAuth}> {children} </ConvexProviderWithClerk> </ClerkProvider> ); } ``` 請查看[Convex Quickstart](https://docs.convex.dev/quickstart/nextjs)和[Convex Clerk](https://docs.convex.dev/auth/clerk) auth 部分以了解更多詳細資訊。 設定我們的架構 ------- 您可以在有或沒有模式的情況下使用 Convex。就我而言,我知道資料的結構並想要定義它,所以我在下面這樣做了。這也為您提供了一個非常好的類型安全 API,可以在與資料庫互動時使用。我們定義兩個表格-一個用於儲存所有語音註解資訊的`notes`表和用於提取的操作專案的`actionItems`表。我們還將定義索引,以便能夠透過`userId`和`noteId`快速查詢資料。 ``` import { defineSchema, defineTable } from 'convex/server'; import { v } from 'convex/values'; export default defineSchema({ notes: defineTable({ userId: v.string(), audioFileId: v.string(), audioFileUrl: v.string(), title: v.optional(v.string()), transcription: v.optional(v.string()), summary: v.optional(v.string()), embedding: v.optional(v.array(v.float64())), generatingTranscript: v.boolean(), generatingTitle: v.boolean(), generatingActionItems: v.boolean(), }) .index('by_userId', ['userId']) .vectorIndex('by_embedding', { vectorField: 'embedding', dimensions: 768, filterFields: ['userId'], }), actionItems: defineTable({ noteId: v.id('notes'), userId: v.string(), task: v.string(), }) .index('by_noteId', ['noteId']) .index('by_userId', ['userId']), }); ``` 儀表板 --- 現在我們已經有了後端和身份驗證設定以及模式,我們可以看看如何獲取資料。登入應用程式後,用戶可以查看其儀表板,其中列出了他們錄製的所有語音筆記。 ![儀表板](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6u9f1b60kgfp4txbszur.png) 為此,我們首先在凸資料夾中定義一個查詢,該查詢使用 auth 接收`userId` ,驗證其有效,並傳回與使用者的`userId`相符的所有註解。 ``` export const getNotes = queryWithUser({ args: {}, handler: async (ctx, args) => { const userId = ctx.userId; if (userId === undefined) { return null; } const notes = await ctx.db .query('notes') .withIndex('by_userId', (q) => q.eq('userId', userId)) .collect(); const results = Promise.all( notes.map(async (note) => { const count = ( await ctx.db .query('actionItems') .withIndex('by_noteId', (q) => q.eq('noteId', note._id)) .collect() ).length; return { count, ...note, }; }), ); return results; }, }); ``` 之後,我們可以透過凸提供的函數使用使用者的驗證令牌來呼叫此`getNotes`查詢,以在儀表板中顯示所有使用者的註解。我們使用伺服器端渲染在伺服器上取得此資料,然後將其傳遞到`<DashboardHomePage />`客戶端元件。這也確保了客戶端上的資料也保持最新。 ``` import { api } from '@/convex/_generated/api'; import { preloadQuery } from 'convex/nextjs'; import DashboardHomePage from './dashboard'; import { getAuthToken } from '../auth'; const ServerDashboardHomePage = async () => { const token = await getAuthToken(); const preloadedNotes = await preloadQuery(api.notes.getNotes, {}, { token }); return <DashboardHomePage preloadedNotes={preloadedNotes} />; }; export default ServerDashboardHomePage; ``` 錄製語音筆記 ------ 最初,使用者的儀表板上不會有任何語音註釋,因此他們可以點擊「錄製新語音註釋」按鈕來錄製。他們將看到以下螢幕,允許他們進行錄製。 ![錄製語音筆記頁面](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e3lm22akd3zanf3ar0za.png) 這將使用本機瀏覽器 API 錄製語音筆記,將檔案保存在 Convex 檔案儲存中,然後透過 Replicate 將其傳送至 Whisper 進行轉錄。我們要做的第一件事是在凸資料夾中定義一個`createNote`突變,它將接收此記錄,在凸資料庫中保存一些訊息,然後呼叫耳語操作。 ``` export const createNote = mutationWithUser({ args: { storageId: v.id('_storage'), }, handler: async (ctx, { storageId }) => { const userId = ctx.userId; let fileUrl = (await ctx.storage.getUrl(storageId)) as string; const noteId = await ctx.db.insert('notes', { userId, audioFileId: storageId, audioFileUrl: fileUrl, generatingTranscript: true, generatingTitle: true, generatingActionItems: true, }); await ctx.scheduler.runAfter(0, internal.whisper.chat, { fileUrl, id: noteId, }); return noteId; }, }); ``` 耳語動作如下圖所示。它使用 Replicate 作為 Whisper 的託管提供者。 ``` export const chat = internalAction({ args: { fileUrl: v.string(), id: v.id('notes'), }, handler: async (ctx, args) => { const replicateOutput = (await replicate.run( 'openai/whisper:4d50797290df275329f202e48c76360b3f22b08d28c196cbc54600319435f8d2', { input: { audio: args.fileUrl, model: 'large-v3', translate: false, temperature: 0, transcription: 'plain text', suppress_tokens: '-1', logprob_threshold: -1, no_speech_threshold: 0.6, condition_on_previous_text: true, compression_ratio_threshold: 2.4, temperature_increment_on_fallback: 0.2, }, }, )) as whisperOutput; const transcript = replicateOutput.transcription || 'error'; await ctx.runMutation(internal.whisper.saveTranscript, { id: args.id, transcript, }); }, }); ``` 此外,所有這些檔案都可以在 Convex 儀表板的「檔案」下看到。 ![凸形儀表板](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mz51ysreunwsk52tqjr9.png) 生成行動專案 ------ 使用者完成語音記錄並透過耳語進行轉錄後,輸出將傳遞到 Together AI 中。我們同時顯示此加載畫面。 ![頁面載入](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1rcr80meap2xql9nrzlf.png) 我們首先定義一個我們希望輸出所在的模式。然後,我們將此模式傳遞到 Together.ai 上託管的 Mixtral 模型中,並提示辨識語音註釋的摘要、文字記錄,並根據成績單。然後我們將所有這些資訊保存到 Convex 資料庫中。為此,我們在凸資料夾中建立一個凸動作。 ``` // convex/together.ts const NoteSchema = z.object({ title: z .string() .describe('Short descriptive title of what the voice message is about'), summary: z .string() .describe( 'A short summary in the first person point of view of the person recording the voice message', ) .max(500), actionItems: z .array(z.string()) .describe( 'A list of action items from the voice note, short and to the point. Make sure all action item lists are fully resolved if they are nested', ), }); export const chat = internalAction({ args: { id: v.id('notes'), transcript: v.string(), }, handler: async (ctx, args) => { const { transcript } = args; const extract = await client.chat.completions.create({ messages: [ { role: 'system', content: 'The following is a transcript of a voice message. Extract a title, summary, and action items from it and answer in JSON in this format: {title: string, summary: string, actionItems: [string, string, ...]}', }, { role: 'user', content: transcript }, ], model: 'mistralai/Mixtral-8x7B-Instruct-v0.1', response_model: { schema: NoteSchema, name: 'SummarizeNotes' }, max_tokens: 1000, temperature: 0.6, max_retries: 3, }); const { title, summary, actionItems } = extract; await ctx.runMutation(internal.together.saveSummary, { id: args.id, summary, actionItems, title, }); }); ``` 當 Together.ai 做出回應時,我們會看到最終畫面,使用者可以在左側的記錄和摘要之間切換,並查看並勾選右側的操作專案。 ![完整語音筆記頁面](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cnd6j68hgusa0aj2buhv.png) 向量搜尋 ---- 該應用程式的最後一部分是向量搜尋。我們使用 Together.ai 嵌入來嵌入文字記錄,並使人們可以根據文字記錄的語義在儀表板中進行搜尋。 我們透過在凸資料夾中建立一個`similarNotes`操作來實現此目的,該操作接受使用者的搜尋查詢,為其產生嵌入,並找到要在頁面上顯示的最相似的註釋。 ``` export const similarNotes = actionWithUser({ args: { searchQuery: v.string(), }, handler: async (ctx, args): Promise<SearchResult[]> => { // 1. Create the embedding const getEmbedding = await togetherai.embeddings.create({ input: [args.searchQuery.replace('/n', ' ')], model: 'togethercomputer/m2-bert-80M-32k-retrieval', }); const embedding = getEmbedding.data[0].embedding; // 2. Then search for similar notes const results = await ctx.vectorSearch('notes', 'by_embedding', { vector: embedding, limit: 16, filter: (q) => q.eq('userId', ctx.userId), // Only search my notes. }); return results.map((r) => ({ id: r._id, score: r._score, })); }, }); ``` 結論 -- 就像這樣,我們建立了一個可投入生產的全端人工智慧應用程式,配備身份驗證、資料庫、儲存和 API。請隨意查看[notesGPT,](https://usenotesgpt.com/)以從您的筆記或[GitHub 儲存庫](https://github.com/nutlope/notesGPT)產生操作專案以供參考。如果您有任何疑問,[請私訊我](twitter.com/nutlope),我將非常樂意回答! --- 原文出處:https://dev.to/nutlope/how-i-built-notesgpt-a-full-stack-ai-voice-note-app-265o

70 個 JavaScript 面試問題

嗨大家好,新年快樂:煙火::煙火::煙火:! ---------------------- 這是一篇很長的文章,所以請耐心聽我一秒鐘或一個小時。每個問題的每個答案都有一個向上箭頭**↑**連結,可讓您返回到問題列表,這樣您就不會浪費時間上下滾動。 ### 問題 - [1. `undefined`和`null`有什麼差別?](#1-whats-the-difference-between-undefined-and-null) - [2. &amp;&amp; 運算子的作用是什麼?](#2-what-does-the-ampamp-operator-do) - [3. || 是什麼意思?運營商做什麼?](#3-what-does-the-operator-do) - [4. 使用 + 或一元加運算子是將字串轉換為數字的最快方法嗎?](#4-is-using-the-or-unary-plus-operator-the-fastest-way-in-converting-a-string-to-a-number) - [5.什麼是DOM?](#5-what-is-the-dom) - [6.什麼是事件傳播?](#6-what-is-event-propagation) - [7.什麼是事件冒泡?](#7-whats-event-bubbling) - [8. 什麼是事件擷取?](#8-whats-event-capturing) - [9. `event.preventDefault()`和`event.stopPropagation()`方法有什麼差別?](#9-whats-the-difference-between-eventpreventdefault-and-eventstoppropagation-methods) - [10. 如何知道元素中是否使用了`event.preventDefault()`方法?](#10-how-to-know-if-the-eventpreventdefault-method-was-used-in-an-element) - [11. 為什麼這段程式碼 obj.someprop.x 會拋出錯誤?](#11-why-does-this-code-objsomepropx-throw-an-error) - \[12.什麼是`event.target` ?\](#12-什麼是 eventtarget- ) - [13.什麼是`event.currentTarget` ?](#13-what-is-eventcurrenttarget) - [14. `==`和`===`有什麼差別?](#14-whats-the-difference-between-and-) - [15. 為什麼在 JavaScript 中比較兩個相似的物件時回傳 false?](#15-why-does-it-return-false-when-comparing-two-similar-objects-in-javascript) - [16. `!!`是什麼意思?運營商做什麼?](#16-what-does-the-operator-do) - [17. 如何計算一行中的多個表達式?](#17-how-to-evaluate-multiple-expressions-in-one-line) - [18.什麼是吊裝?](#18-what-is-hoisting) - [19.什麼是範圍?](#19-what-is-scope) - [20.什麼是閉包?](#20-what-are-closures) - [21. JavaScript 中的假值是什麼?](#21-what-are-the-falsy-values-in-javascript) - [22. 如何檢查一個值是否為假值?](#22-how-to-check-if-a-value-is-falsy) - [23. `"use strict"`有什麼作用?](#23-what-does-use-strict-do) - [24. JavaScript 中`this`的值是什麼?](#24-whats-the-value-of-this-in-javascript) - [25. 物件的`prototype`是什麼?](#25-what-is-the-prototype-of-an-object) - \[26.什麼是 IIFE,它有什麼用?\](#26-what-is-an-iife-what-is-the-use-of-it ) - [27. `Function.prototype.apply`方法有什麼用?](#27-what-is-the-use-functionprototypeapply-method) - [28. `Function.prototype.call`方法有什麼用?](#28-what-is-the-use-functionprototypecall-method) - [29. `Function.prototype.apply`和`Function.prototype.call`有什麼差別?](#29-whats-the-difference-between-functionprototypeapply-and-functionprototypecall) - [30. `Function.prototype.bind`的用法是什麼?](#30-what-is-the-usage-of-functionprototypebind) - \[31.什麼是函數式程式設計以及 JavaScript 的哪些特性使其成為函數式語言的候選者?\](#31-什麼是函數式程式設計和 javascript 的特性是什麼-使其成為函數式語言的候選者 ) - [32.什麼是高階函數?](#32-what-are-higher-order-functions) - [33.為什麼函數被稱為First-class Objects?](#33-why-are-functions-called-firstclass-objects) - \[34.手動實作`Array.prototype.map`方法。\](#34-手動實作 arrayprototypemap-method ) - [35. 手動實作`Array.prototype.filter`方法。](#35-implement-the-arrayprototypefilter-method-by-hand) - [36. 手動實作`Array.prototype.reduce`方法。](#36-implement-the-arrayprototypereduce-method-by-hand) - [37.什麼是`arguments`物件?](#37-what-is-the-arguments-object) - [38. 如何創造沒有**原型的**物件?](#38-how-to-create-an-object-without-a-prototype) - [39. 為什麼當你呼叫這個函數時,這段程式碼中的`b`會變成全域變數?](#39-why-does-b-in-this-code-become-a-global-variable-when-you-call-this-function) - [40.什麼是**ECMAScript** ?](#40-what-is-ecmascript) - [41. **ES6**或**ECMAScript 2015**有哪些新功能?](#41-what-are-the-new-features-in-es6-or-ecmascript-2015) - [42. `var` 、 `let`和`const`關鍵字有什麼差別?](#42-whats-the-difference-between-var-let-and-const-keywords) - [43. 什麼是**箭頭函數**?](#43-what-are-arrow-functions) - [44.什麼是**類別**?](#44-what-are-classes) - [45.什麼是**模板文字**?](#45-what-are-template-literals) - [46.什麼是**物件解構**?](#46-what-is-object-destructuring) - [47.什麼是`ES6 Modules` ?](#47-what-are-es6-modules) - [48.什麼是`Set`物件以及它如何運作?](#48-what-is-the-set-object-and-how-does-it-work) - [49. 什麼是回呼函數?](#49-what-is-a-callback-function) - [50. 什麼是**Promise** ?](#50-what-are-promises) - [51. 什麼是*async/await*以及它是如何運作的?](#51-what-is-asyncawait-and-how-does-it-work) - [52. **Spread 運算子**和**Rest 運算**子有什麼差別?](#52-whats-the-difference-between-spread-operator-and-rest-operator) - [53. 什麼是**預設參數**?](#53-what-are-default-parameters) - [54.什麼是**包裝物件**?](#54-what-are-wrapper-objects) - [55.**隱性強制**和**顯性**強制有什麼差別?](#55-what-is-the-difference-between-implicit-and-explicit-coercion) - [56. 什麼是`NaN` ?以及如何檢查值是否為`NaN` ?](#56-what-is-nan-and-how-to-check-if-a-value-is-nan) - [57. 如何檢查一個值是否為一個**陣列**?](#57-how-to-check-if-a-value-is-an-array) - [58. 如何在不使用`%`或模運算子的情況下檢查數字是否為偶數?](#58-how-to-check-if-a-number-is-even-without-using-the-or-modulo-operator) - [59. 如何檢查物件中是否存在某個屬性?](#59-how-to-check-if-a-certain-property-exists-in-an-object) - [60.什麼是**AJAX** ?](#60-what-is-ajax) - [61. JavaScript 中建立物件的方式有哪些?](#61-what-are-the-ways-of-making-objects-in-javascript) - [62. `Object.seal`和`Object.freeze`方法有什麼不同?](#62-whats-the-difference-between-objectseal-and-objectfreeze-methods) - [63. `in`運算子和物件中的`hasOwnProperty`方法有什麼差別?](#63-whats-the-difference-between-the-in-operator-and-the-hasownproperty-method-in-objects) - [64. JavaScript中處理**非同步程式碼的**方法有哪些?](#64-what-are-the-ways-to-deal-with-asynchronous-code-in-javasscript) - [65.**函數表達式**和**函數宣告**有什麼不同?](#65-whats-the-difference-between-a-function-expression-and-function-declaration) - \[66.一個函數有多少種*呼叫*方式?\]( 66-函數可以有多少種方式被呼叫) ================= - [67. 什麼是*記憶*,它有什麼用?](#67-what-is-memoization-and-whats-the-use-it) - [68. 實現記憶輔助功能。](#68-implement-a-memoization-helper-function) - [69. 為什麼`typeof null`回傳`object` ?如何檢查一個值是否為`null` ?](#69-why-does-typeof-null-return-object-how-to-check-if-a-value-is-null) - [`new`關鍵字有什麼作用?](#70-what-does-the-new-keyword-do) ### 1. `undefined`和`null`有什麼差別? [^](#the-questions "返回問題")在了解`undefined`和`null`之間的差異之前,我們必須先了解它們之間的相似之處。 - 它們屬於**JavaScript 的**7 種基本型別。 ``` let primitiveTypes = ['string','number','null','undefined','boolean','symbol', 'bigint']; ``` - 它們是**虛假的**價值觀。使用`Boolean(value)`或`!!value`將其轉換為布林值時計算結果為 false 的值。 ``` console.log(!!null); //logs false console.log(!!undefined); //logs false console.log(Boolean(null)); //logs false console.log(Boolean(undefined)); //logs false ``` 好吧,我們來談談差異。 - `undefined`是尚未指派特定值的變數的預設值。或一個沒有**明確**回傳值的函數。 `console.log(1)` 。或物件中不存在的屬性。 JavaScript 引擎為我們完成了**指派**`undefined`值的任務。 ``` let _thisIsUndefined; const doNothing = () => {}; const someObj = { a : "ay", b : "bee", c : "si" }; console.log(_thisIsUndefined); //logs undefined console.log(doNothing()); //logs undefined console.log(someObj["d"]); //logs undefined ``` - `null`是**「代表無值的值」** 。 `null`是已**明確**定義給變數的值。在此範例中,當`fs.readFile`方法未引發錯誤時,我們得到`null`值。 ``` fs.readFile('path/to/file', (e,data) => { console.log(e); //it logs null when no error occurred if(e){ console.log(e); } console.log(data); }); ``` 當比較`null`和`undefined`時,使用`==`時我們得到`true` ,使用`===`時得到`false` 。您可以[在此處](#14-whats-the-difference-between-and-)閱讀原因。 ``` console.log(null == undefined); // logs true console.log(null === undefined); // logs false ``` ### 2. `&&`運算子的作用是什麼? [^](#the-questions "返回問題") `&&`或**邏輯 AND**運算子在其運算元中尋找第一個*假*表達式並傳回它,如果沒有找到任何*假*表達式,則傳回最後一個表達式。它採用短路來防止不必要的工作。在我的一個專案中關閉資料庫連線時,我在`catch`區塊中使用了它。 ``` console.log(false && 1 && []); //logs false console.log(" " && true && 5); //logs 5 ``` 使用**if**語句。 ``` const router: Router = Router(); router.get('/endpoint', (req: Request, res: Response) => { let conMobile: PoolConnection; try { //do some db operations } catch (e) { if (conMobile) { conMobile.release(); } } }); ``` 使用**&amp;&amp;**運算子。 ``` const router: Router = Router(); router.get('/endpoint', (req: Request, res: Response) => { let conMobile: PoolConnection; try { //do some db operations } catch (e) { conMobile && conMobile.release() } }); ``` ### 3. `||`是什麼意思?運營商做什麼? [↑](#the-questions "返回問題") `||` or**邏輯 OR**運算子尋找其運算元中的第一個*真值*表達式並傳回它。這也採用短路來防止不必要的工作。在**ES6預設函數參數**被支援之前,它被用來初始化函數中的預設參數值。 ``` console.log(null || 1 || undefined); //logs 1 function logName(name) { var n = name || "Mark"; console.log(n); } logName(); //logs "Mark" ``` ### 4. 使用**+**或一元加運算子是將字串轉換為數字的最快方法嗎? [^](#the-questions "返回問題")根據[MDN 文件,](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus) `+`是將字串轉換為數字的最快方法,因為如果該值已經是數字,它不會對該值執行任何操作。 ### 5.什麼是**DOM** ? [^](#the-questions "返回問題") **DOM**代表**文件物件模型,**是 HTML 和 XML 文件的介面 ( **API** )。當瀏覽器第一次讀取(*解析*)我們的 HTML 文件時,它會建立一個大物件,一個基於 HTML 文件的非常大的物件,這就是**DOM** 。它是根據 HTML 文件建模的樹狀結構。 **DOM**用於互動和修改**DOM 結構**或特定元素或節點。 想像一下,如果我們有這樣的 HTML 結構。 ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document Object Model</title> </head> <body> <div> <p> <span></span> </p> <label></label> <input> </div> </body> </html> ``` 等效的**DOM**應該是這樣的。 ![DOM 等效項](https://thepracticaldev.s3.amazonaws.com/i/mbqphfbjfie45ynj0teo.png) **JavaScript**中的`document`物件代表**DOM** 。它為我們提供了許多方法,我們可以用來選擇元素來更新元素內容等等。 ### 6.什麼是**事件傳播**? [↑](#the-questions "返回問題")當某個**事件**發生在**DOM**元素上時,該**事件**並非完全發生在該元素上。在**冒泡階段**,**事件**向上冒泡,或到達其父級、祖父母、祖父母的父級,直到一直到達`window` ,而在**捕獲階段**,事件從`window`開始向下到達觸發的元素事件或`<a href="#12-what-is-eventtarget-">event.target</a>` 。 **事件傳播**分為**三個**階段。 1. [捕獲階段](#8-whats-event-capturing)-事件從`window`開始,然後向下到達每個元素,直到到達目標元素。 2. [目標階段](#12-what-is-eventtarget-)– 事件已到達目標元素。 3. [冒泡階段](#7-whats-event-bubbling)-事件從目標元素冒起,然後向上移動到每個元素,直到到達`window` 。 ![事件傳播](https://thepracticaldev.s3.amazonaws.com/i/hjayqa99iejfhbsujlqd.png) ### 7.什麼是**事件冒泡**? [↑](#the-questions "返回問題")當某個**事件**發生在**DOM**元素上時,該**事件**並非完全發生在該元素上。在**冒泡階段**,**事件**向上冒泡,或到達其父級、祖父母、祖父母的父級,直到一直到達`window` 。 如果我們有一個像這樣的範例標記。 ``` <div class="grandparent"> <div class="parent"> <div class="child">1</div> </div> </div> ``` 還有我們的js程式碼。 ``` function addEvent(el, event, callback, isCapture = false) { if (!el || !event || !callback || typeof callback !== 'function') return; if (typeof el === 'string') { el = document.querySelector(el); }; el.addEventListener(event, callback, isCapture); } addEvent(document, 'DOMContentLoaded', () => { const child = document.querySelector('.child'); const parent = document.querySelector('.parent'); const grandparent = document.querySelector('.grandparent'); addEvent(child, 'click', function (e) { console.log('child'); }); addEvent(parent, 'click', function (e) { console.log('parent'); }); addEvent(grandparent, 'click', function (e) { console.log('grandparent'); }); addEvent(document, 'click', function (e) { console.log('document'); }); addEvent('html', 'click', function (e) { console.log('html'); }) addEvent(window, 'click', function (e) { console.log('window'); }) }); ``` `addEventListener`方法有第三個可選參數**useCapture ,**預設值為`false`事件將在**冒泡階段**發生,如果為`true` ,事件將在**捕獲階段**發生。如果我們點擊`child`元素,它會分別在**控制台**上記錄`child` 、 `parent`元素、 `grandparent` 、 `html` 、 `document`和`window` 。這就是**事件冒泡**。 ### 8. 什麼是**事件擷取**? [↑](#the-questions "返回問題")當某個**事件**發生在**DOM**元素上時,該**事件**並非完全發生在該元素上。在**捕獲階段**,事件從`window`開始一直到觸發事件的元素。 如果我們有一個像這樣的範例標記。 ``` <div class="grandparent"> <div class="parent"> <div class="child">1</div> </div> </div> ``` 還有我們的js程式碼。 ``` function addEvent(el, event, callback, isCapture = false) { if (!el || !event || !callback || typeof callback !== 'function') return; if (typeof el === 'string') { el = document.querySelector(el); }; el.addEventListener(event, callback, isCapture); } addEvent(document, 'DOMContentLoaded', () => { const child = document.querySelector('.child'); const parent = document.querySelector('.parent'); const grandparent = document.querySelector('.grandparent'); addEvent(child, 'click', function (e) { console.log('child'); }, true); addEvent(parent, 'click', function (e) { console.log('parent'); }, true); addEvent(grandparent, 'click', function (e) { console.log('grandparent'); }, true); addEvent(document, 'click', function (e) { console.log('document'); }, true); addEvent('html', 'click', function (e) { console.log('html'); }, true) addEvent(window, 'click', function (e) { console.log('window'); }, true) }); ``` `addEventListener`方法有第三個可選參數**useCapture ,**預設值為`false`事件將在**冒泡階段**發生,如果為`true` ,事件將在**捕獲階段**發生。如果我們點擊`child`元素,它會分別在**控制台**上記錄`window` 、 `document` 、 `html` 、 `grandparent` 、 `parent`和`child` 。這就是**事件捕獲**。 ### 9. `event.preventDefault()`和`event.stopPropagation()`方法有什麼差別? [↑](#the-questions "返回問題") `event.preventDefault()`方法**阻止**元素的預設行為。如果在`form`元素中使用,它**會阻止**其提交。如果在`anchor`元素中使用,它**會阻止**其導航。如果在`contextmenu`中使用,它**會阻止**其顯示或顯示。而`event.stopPropagation()`方法會停止事件的傳播或停止事件在[冒泡](#7-whats-event-bubbling)或[捕獲](#8-whats-event-capturing)階段發生。 ### 10. 如何知道元素中是否使用了`event.preventDefault()`方法? [↑](#the-questions "返回問題")我們可以使用事件物件中的`event.defaultPrevented`屬性。它傳回一個`boolean` ,指示是否在特定元素中呼叫了`event.preventDefault()` 。 ### 11. 為什麼這段程式碼`obj.someprop.x`會拋出錯誤? ``` const obj = {}; console.log(obj.someprop.x); ``` [^](#the-questions "返回問題")顯然,由於我們嘗試存取 a 的原因,這會引發錯誤 `someprop`屬性中的`x`屬性具有`undefined`值。請記住,物件中的**屬性**本身並不存在,且其**原型**具有預設值`undefined`且`undefined`沒有屬性`x` 。 ### 12.什麼是**event.target** ? [↑](#the-questions "返回問題")最簡單來說, **event.target**是**發生**事件的元素或**觸發**事件的元素。 HTML 標記範例。 ``` <div onclick="clickFunc(event)" style="text-align: center;margin:15px; border:1px solid red;border-radius:3px;"> <div style="margin: 25px; border:1px solid royalblue;border-radius:3px;"> <div style="margin:25px;border:1px solid skyblue;border-radius:3px;"> <button style="margin:10px"> Button </button> </div> </div> </div> ``` JavaScript 範例。 ``` function clickFunc(event) { console.log(event.target); } ``` 如果您單擊按鈕,它會記錄**按鈕**標記,即使我們將事件附加在最外部的`div`上,它也會始終記錄**按鈕**,因此我們可以得出結論, **event.target**是觸發事件的元素。 ### 13.什麼是**event.currentTarget** ? [↑](#the-questions "返回問題") **event.currentTarget**是我們**明確**附加事件處理程序的元素。 複製**問題 12**中的標記。 HTML 標記範例。 ``` <div onclick="clickFunc(event)" style="text-align: center;margin:15px; border:1px solid red;border-radius:3px;"> <div style="margin: 25px; border:1px solid royalblue;border-radius:3px;"> <div style="margin:25px;border:1px solid skyblue;border-radius:3px;"> <button style="margin:10px"> Button </button> </div> </div> </div> ``` 並且稍微改變我們的**JS** 。 ``` function clickFunc(event) { console.log(event.currentTarget); } ``` 如果您按一下該按鈕,即使我們按一下該按鈕,它也會記錄最外層的**div**標記。在此範例中,我們可以得出結論, **event.currentTarget**是我們附加事件處理程序的元素。 ### 14. `==`和`===`有什麼差別? [^](#the-questions "返回問題") `==` \_\_(抽象相等)\_\_ 和`===` \_\_(嚴格相等)\_\_ 之間的區別在於`==`在*強制轉換*後按**值**進行比較,而`===`在不進行*強制轉換的*情況下按**值**和**類型**進行比較。 讓我們更深入地研究`==` 。那麼首先我們來談談*強制*。 *強制轉換*是將一個值轉換為另一種類型的過程。在本例中, `==`進行*隱式強制轉換*。在比較兩個值之前, `==`需要執行一些條件。 假設我們必須比較`x == y`值。 1. 如果`x`和`y`具有相同的類型。 然後將它們與`===`運算子進行比較。 2. 如果`x`為`null`且`y` `undefined` ,則傳回`true` 。 3. 如果`x` `undefined`且`y`為`null`則傳回`true` 。 4. 如果`x`是`number`類型, `y`是`string`類型 然後回傳`x == toNumber(y)` 。 5. 如果`x`是`string`類型, `y`是`number`類型 然後返回`toNumber(x) == y` 。 6. 如果`x`是`boolean`類型 然後返回`toNumber(x) == y` 。 7. 如果`y`是`boolean`類型 然後回傳`x == toNumber(y)` 。 8. 如果`x`是`string` 、 `symbol`或`number`且`y`是 type `object` 然後回傳`x == toPrimitive(y)` 。 9. 如果`x`是`object`且`x`是`string` 、 `symbol` 然後返回`toPrimitive(x) == y` 。 10. 返回`false` 。 **注意:** `toPrimitive`首先使用物件中的`valueOf`方法,然後使用`toString`方法來取得該物件的原始值。 讓我們舉個例子。 | `x` | `y` | `x == y` | | ------------- |:-------------:| ----------------: | | `5` | `5` | `true` | | `1` | `'1'` | `true` | | `null` | `undefined` | `true` | | `0` | `false` | `true` | | `'1,2'` | `[1,2]` | `true` | | `'[object Object]'` | `{}` | `true` | 這些範例都傳回`true` 。 **第一個範例**屬於**條件一**,因為`x`和`y`具有相同的類型和值。 **第二個範例**轉到**條件四,**在比較之前將`y`轉換為`number` 。 **第三個例子**涉及**條件二**。 **第四個範例**轉到**條件七,**因為`y`是`boolean` 。 **第五個範例**適用於**條件八**。使用`toString()`方法將陣列轉換為`string` ,該方法傳回`1,2` 。 **最後一個例子**適用於**條件十**。使用傳回`[object Object]`的`toString()`方法將該物件轉換為`string` 。 | `x` | `y` | `x === y` | | ------------- |:-------------:| ----------------: | | `5` | `5` | `true` | | `1` | `'1'` | `false` | | `null` | `undefined` | `false` | | `0` | `false` | `false` | | `'1,2'` | `[1,2]` | `false` | | `'[object Object]'` | `{}` | `false` | 如果我們使用`===`運算符,則除第一個範例之外的所有比較都將傳回`false` ,因為它們不具有相同的類型,而第一個範例將傳回`true` ,因為兩者俱有相同的類型和值。 ### 15. 為什麼在 JavaScript 中比較兩個相似的物件時回傳**false** ? [^](#the-questions "返回問題")假設我們有下面的例子。 ``` let a = { a: 1 }; let b = { a: 1 }; let c = a; console.log(a === b); // logs false even though they have the same property console.log(a === c); // logs true hmm ``` **JavaScript**以不同的方式比較*物件*和*基元*。在*基元*中,它透過**值**來比較它們,而在*物件*中,它透過**引用**或**儲存變數的記憶體位址**來比較它們。這就是為什麼第一個`console.log`語句回傳`false`而第二個`console.log`語句回傳`true`的原因。 `a`和`c`有相同的引用,而`a`和`b`則不同。 ### 16. **!!**是什麼意思?運營商做什麼? [↑](#the-questions "返回問題")**雙非**運算子或**!!**將右側的值強制轉換為布林值。基本上,這是一種將值轉換為布林值的奇特方法。 ``` console.log(!!null); //logs false console.log(!!undefined); //logs false console.log(!!''); //logs false console.log(!!0); //logs false console.log(!!NaN); //logs false console.log(!!' '); //logs true console.log(!!{}); //logs true console.log(!![]); //logs true console.log(!!1); //logs true console.log(!![].length); //logs false ``` ### 17. 如何計算一行中的多個表達式? [↑](#the-questions "返回問題")我們可以使用`,`或逗號運算子來計算一行中的多個表達式。它從左到右計算並傳回右側最後一項或最後一個操作數的值。 ``` let x = 5; x = (x++ , x = addFive(x), x *= 2, x -= 5, x += 10); function addFive(num) { return num + 5; } ``` 如果記錄`x`的值,它將是**27** 。首先,我們**增加**x 的值,它將是**6** ,然後我們呼叫函數`addFive(6)`並將 6 作為參數傳遞,並將結果分配給`x` , `x`的新值將是**11** 。之後,我們將`x`的當前值乘以**2**並將其分配給`x` , `x`的更新值將是**22** 。然後,我們將`x`的當前值減去 5 並將結果指派給`x` ,更新後的值將是**17** 。最後,我們將`x`的值增加 10 並將更新後的值指派給`x` ,現在`x`的值將是**27** 。 ### 18.什麼是**吊裝**? [^](#the-questions "返回問題")**提升**是一個術語,用於描述將*變數*和*函數*移動到其*(全域或函數)*作用域的頂部(即我們定義該變數或函數的位置)。 要理解**提升**,我必須解釋*執行上下文*。 **執行上下文**是目前正在執行的「程式碼環境」。**執行上下文**有兩個階段*:編譯*和*執行*。 **編譯**- 在此階段,它獲取所有*函數聲明*並將它們*提升*到作用域的頂部,以便我們稍後可以引用它們並獲取所有*變數聲明***(使用 var 關鍵字聲明)** ,並將它們*提升*並給它們一個默認值*未定義*的 . **執行**- 在此階段,它將值指派給先前*提升的*變數,並*執行*或*呼叫*函數**(物件中的方法)** 。 **注意:**只有使用*var*關鍵字宣告的**函數宣告**和變數才會*被提升*,而不是**函數表達式**或**箭頭函數**、 `let`和`const`關鍵字。 好吧,假設我們在下面的*全域範圍*內有一個範例程式碼。 ``` console.log(y); y = 1; console.log(y); console.log(greet("Mark")); function greet(name){ return 'Hello ' + name + '!'; } var y; ``` 此程式碼記錄`undefined` , `1` , `Hello Mark!`分別。 所以*編譯*階段看起來像這樣。 ``` function greet(name) { return 'Hello ' + name + '!'; } var y; //implicit "undefined" assignment //waiting for "compilation" phase to finish //then start "execution" phase /* console.log(y); y = 1; console.log(y); console.log(greet("Mark")); */ ``` 出於範例目的,我對變數和*函數呼叫*的*賦值*進行了評論。 *編譯*階段完成後,它開始*執行*階段,呼叫方法並向變數賦值。 ``` function greet(name) { return 'Hello ' + name + '!'; } var y; //start "execution" phase console.log(y); y = 1; console.log(y); console.log(greet("Mark")); ``` ### 19.什麼是**範圍**? [↑](#the-questions "返回問題") JavaScript 中的**作用域**是我們可以有效存取變數或函數的**區域**。 JavaScript 有三種類型的作用域。**全域作用域**、**函數作用域**和**區塊作用域(ES6)** 。 - **全域作用域**- 在全域命名空間中宣告的變數或函數位於全域作用域中,因此可以在程式碼中的任何位置存取。 ``` //global namespace var g = "global"; function globalFunc(){ function innerFunc(){ console.log(g); // can access "g" because "g" is a global variable } innerFunc(); } ``` - **函數作用域**- 函數內聲明的變數、函數和參數可以在該函數內部存取,但不能在函數外部存取。 ``` function myFavoriteFunc(a) { if (true) { var b = "Hello " + a; } return b; } myFavoriteFunc("World"); console.log(a); // Throws a ReferenceError "a" is not defined console.log(b); // does not continue here ``` - **區塊作用域**- 在區塊`{}`內宣告的變數**( `let` 、 `const` )**只能在區塊內存取。 ``` function testBlock(){ if(true){ let z = 5; } return z; } testBlock(); // Throws a ReferenceError "z" is not defined ``` **範圍**也是一組查找變數的規則。如果一個變數在**當前作用域中**不存在,它會在**外部作用域中查找**並蒐索該變數,如果不存在,它會再次**查找,**直到到達**全域作用域。**如果該變數存在,那麼我們可以使用它,如果不存在,我們可以使用它來拋出錯誤。它搜尋**最近的**變數,一旦找到它就停止**搜尋**或**尋找**。這稱為**作用域鏈**。 ``` /* Scope Chain Inside inner function perspective inner's scope -> outer's scope -> global's scope */ //Global Scope var variable1 = "Comrades"; var variable2 = "Sayonara"; function outer(){ //outer's scope var variable1 = "World"; function inner(){ //inner's scope var variable2 = "Hello"; console.log(variable2 + " " + variable1); } inner(); } outer(); // logs Hello World // because (variable2 = "Hello") and (variable1 = "World") are the nearest // variables inside inner's scope. ``` ![範圍](https://thepracticaldev.s3.amazonaws.com/i/l81b3nmdonimex0qsgyr.png) ### 20.什麼是**閉包**? [^](#the-questions "返回問題")這可能是所有這些問題中最難的問題,因為**閉包**是一個有爭議的話題。那我就從我的理解來解釋。 **閉包**只是函數在宣告時記住其當前作用域、其父函數作用域、其父函數的父函數作用域上的變數和參數的引用的能力,直到在**作用域鏈**的幫助下到達全域作用域。基本上它是聲明函數時建立的**作用域**。 例子是解釋閉包的好方法。 ``` //Global's Scope var globalVar = "abc"; function a(){ //testClosures's Scope console.log(globalVar); } a(); //logs "abc" /* Scope Chain Inside a function perspective a's scope -> global's scope */ ``` 在此範例中,當我們宣告`a`函數時**,全域**作用域是`a's`*閉包*的一部分。 ![a的閉包](https://thepracticaldev.s3.amazonaws.com/i/teatokuw4xvgtlzbzhn8.png) 變數`globalVar`在影像中沒有值的原因是該變數的值可以根據我們呼叫`a`**位置**和**時間**而改變。 但在上面的範例中, `globalVar`變數的值為**abc** 。 好吧,讓我們來看一個複雜的例子。 ``` var globalVar = "global"; var outerVar = "outer" function outerFunc(outerParam) { function innerFunc(innerParam) { console.log(globalVar, outerParam, innerParam); } return innerFunc; } const x = outerFunc(outerVar); outerVar = "outer-2"; globalVar = "guess" x("inner"); ``` ![複雜的](https://thepracticaldev.s3.amazonaws.com/i/e4hxm7zvz8eun2ppenwp.png) 這將列印“猜測外部內部”。對此的解釋是,當我們呼叫`outerFunc`函數並將`innerFunc`函數的回傳值指派給變數`x`時,即使我們將新值**outer-2**指派給`outerVar`變數, `outerParam`也會具有**outer**值,因為 重新分配發生在呼叫`outer`函數之後,當我們呼叫`outerFunc`函數時,它會在**作用域鏈**中尋找`outerVar`的值,而`outerVar`的值為**「outer」** 。現在,當我們呼叫引用了`innerFunc`的`x`變數時, `innerParam`的值為**inner,**因為這是我們在呼叫中傳遞的值,而`globalVar`變數的值為**猜測**,因為在呼叫`x`變數之前,我們為`globalVar`分配了一個新值,並且在呼叫`x`時**作用域鏈**中`globalVar`的值是**猜測**。 我們有一個例子來示範沒有正確理解閉包的問題。 ``` const arrFuncs = []; for(var i = 0; i < 5; i++){ arrFuncs.push(function (){ return i; }); } console.log(i); // i is 5 for (let i = 0; i < arrFuncs.length; i++) { console.log(arrFuncs[i]()); // all logs "5" } ``` 由於**Closures**的原因,此程式碼無法按我們的預期工作。 `var`關鍵字建立一個全域變數,當我們推送一個函數時 我們返回全域變數`i` 。因此,當我們在循環之後呼叫該陣列中的其中一個函數時,它會記錄`5` ,因為我們得到 `i`的目前值為`5` ,我們可以存取它,因為它是全域變數。因為**閉包**保留該變數的**引用,**而不是其建立時的**值**。我們可以使用**IIFES**或將`var`關鍵字變更為`let`來解決此問題,以實現區塊作用域。 ### 21. **JavaScript**中的**假**值是什麼? [↑](#the-questions "返回問題") ``` const falsyValues = ['', 0, null, undefined, NaN, false]; ``` **假**值是轉換為布林值時變成**false 的**值。 ### 22. 如何檢查一個值是否為**假值**? [↑](#the-questions "返回問題")使用**布林**函數或雙非運算符**[!!](#16-what-does-the-operator-do)** ### 23. `"use strict"`有什麼作用? [^](#the-questions "返回問題") `"use strict"`是**JavaScript**中的 ES5 功能,它使我們的程式碼在*函數*或*整個腳本*中處於**嚴格模式**。**嚴格模式**幫助我們避免程式碼早期出現**錯誤**並為其加入限制。 **嚴格模式**給我們的限制。 - 分配或存取未宣告的變數。 ``` function returnY(){ "use strict"; y = 123; return y; } ``` - 為唯讀或不可寫的全域變數賦值; ``` "use strict"; var NaN = NaN; var undefined = undefined; var Infinity = "and beyond"; ``` - 刪除不可刪除的屬性。 ``` "use strict"; const obj = {}; Object.defineProperty(obj, 'x', { value : '1' }); delete obj.x; ``` - 參數名稱重複。 ``` "use strict"; function someFunc(a, b, b, c){ } ``` - 使用**eval**函數建立變數。 ``` "use strict"; eval("var x = 1;"); console.log(x); //Throws a Reference Error x is not defined ``` - **該**值的預設值是`undefined` 。 ``` "use strict"; function showMeThis(){ return this; } showMeThis(); //returns undefined ``` **嚴格模式**的限制遠不止這些。 ### 24. JavaScript 中`this`的值是什麼? [↑](#the-questions "返回問題")基本上, `this`是指目前正在執行或呼叫函數的物件的值。我說**目前**是因為**它**的值會根據我們使用它的上下文和使用它的位置而改變。 ``` const carDetails = { name: "Ford Mustang", yearBought: 2005, getName(){ return this.name; }, isRegistered: true }; console.log(carDetails.getName()); // logs Ford Mustang ``` 這是我們通常所期望的,因為在**getName**方法中我們傳回`this.name` ,在此上下文中`this`指的是`carDetails`物件,該物件目前是正在執行的函數的「擁有者」物件。 好吧,讓我們加入一些程式碼讓它變得奇怪。在`console.log`語句下面加入這三行程式碼 ``` var name = "Ford Ranger"; var getCarName = carDetails.getName; console.log(getCarName()); // logs Ford Ranger ``` 第二個`console.log`語句印製了**「Ford Ranger」**一詞,這很奇怪,因為在我們的第一個`console.log`語句中它印了**「Ford Mustang」** 。原因是`getCarName`方法有一個不同的「擁有者」物件,即`window`物件。在全域作用域中使用`var`關鍵字聲明變數會在`window`物件中附加與變數同名的屬性。請記住,當未使用`"use strict"`時,全域範圍內的`this`指的是`window`物件。 ``` console.log(getCarName === window.getCarName); //logs true console.log(getCarName === this.getCarName); // logs true ``` 本例中的`this`和`window`指的是同一個物件。 解決此問題的一種方法是使用函數中的`<a href="#27-what-is-the-use-functionprototypeapply-method">apply</a>`和`<a href="#28-what-is-the-use-functionprototypecall-method">call</a>`方法。 ``` console.log(getCarName.apply(carDetails)); //logs Ford Mustang console.log(getCarName.call(carDetails)); //logs Ford Mustang ``` `apply`和`call`方法期望第一個參數是一個物件,該物件將是該函數內`this`的值。 **IIFE** (即**立即呼叫函數表達式)** 、在全域作用域中宣告的函數、物件內部方法中的**匿名函數**和內部函數都有一個指向**window**物件的預設**值**。 ``` (function (){ console.log(this); })(); //logs the "window" object function iHateThis(){ console.log(this); } iHateThis(); //logs the "window" object const myFavoriteObj = { guessThis(){ function getThis(){ console.log(this); } getThis(); }, name: 'Marko Polo', thisIsAnnoying(callback){ callback(); } }; myFavoriteObj.guessThis(); //logs the "window" object myFavoriteObj.thisIsAnnoying(function (){ console.log(this); //logs the "window" object }); ``` 如果我們想要取得`myFavoriteObj`物件中的`name`屬性**(Marko Polo)**的值,有兩種方法可以解決這個問題。 首先,我們將`this`的值保存在變數中。 ``` const myFavoriteObj = { guessThis(){ const self = this; //saves the this value to the "self" variable function getName(){ console.log(self.name); } getName(); }, name: 'Marko Polo', thisIsAnnoying(callback){ callback(); } }; ``` 在此圖像中,我們保存`this`的值,該值將是`myFavoriteObj`物件。所以我們可以在`getName`內部函數中存取它。 其次,我們使用**ES6[箭頭函數](#43-what-are-arrow-functions)**。 ``` const myFavoriteObj = { guessThis(){ const getName = () => { //copies the value of "this" outside of this arrow function console.log(this.name); } getName(); }, name: 'Marko Polo', thisIsAnnoying(callback){ callback(); } }; ``` [箭頭函數](#43-what-are-arrow-functions)沒有自己的`this` 。它複製封閉詞法範圍的`this`值,或複製`getName`內部函數外部的`this`值(即`myFavoriteObj`物件)。我們也可以根據[函數的呼叫方式](#66-how-many-ways-can-a-function-be-invoked)來決定`this`的值。 ### 25. 物件的`prototype`是什麼? [↑](#the-questions "返回問題")最簡單的`prototype`是一個物件的*藍圖*。如果目前物件中確實存在它,則將其用作**屬性**和**方法**的後備。這是在物件之間共享屬性和功能的方式。這是 JavaScript**原型繼承**的核心概念。 ``` const o = {}; console.log(o.toString()); // logs [object Object] ``` 即使`o.toString`方法不存在於`o`物件中,它也不會拋出錯誤,而是傳回字串`[object Object]` 。當物件中不存在屬性時,它會尋找其**原型**,如果仍然不存在,則會尋找**原型的原型**,依此類推,直到在**原型鏈**中找到具有相同屬性的屬性。**原型鏈**的末尾在**Object.prototype**之後為`null` 。 ``` console.log(o.toString === Object.prototype.toString); // logs true // which means we we're looking up the Prototype Chain and it reached // the Object.prototype and used the "toString" method. ``` ### 26. 什麼是**IIFE** ,它有什麼用? [^](#the-questions "返回問題") **IIFE**或**立即呼叫函數表達式**是在建立或宣告後將被呼叫或執行的函數。建立**IIFE**的語法是,我們將`function (){}`包裝在括號`()`或**分組運算**子內,以將函數視為表達式,然後用另一個括號`()`呼叫它。所以**IIFE**看起來像這樣`(function(){})()` 。 ``` (function () { }()); (function () { })(); (function named(params) { })(); (() => { })(); (function (global) { })(window); const utility = (function () { return { //utilities }; })(); ``` 這些範例都是有效的**IIFE** 。倒數第二個範例顯示我們可以將參數傳遞給**IIFE**函數。最後一個範例表明我們可以將**IIFE**的結果保存到變數中,以便稍後引用它。 **IIFE**的最佳用途是進行初始化設定功能,並避免與全域範圍內的其他變數**發生命名衝突**或污染全域名稱空間。讓我們舉個例子。 ``` <script src="https://cdnurl.com/somelibrary.js"></script> ``` 假設我們有一個指向庫`somelibrary.js`的連結,該庫公開了我們可以在程式碼中使用的一些全域函數,但該庫有兩個我們不使用`createGraph`和`drawGraph`方法,因為這些方法中有錯誤。我們想要實作我們自己的`createGraph`和`drawGraph`方法。 - 解決這個問題的一種方法是改變腳本的結構。 ``` <script src="https://cdnurl.com/somelibrary.js"></script> <script> function createGraph() { // createGraph logic here } function drawGraph() { // drawGraph logic here } </script> ``` 當我們使用這個解決方案時,我們將覆蓋庫為我們提供的這兩種方法。 - 解決這個問題的另一種方法是更改我們自己的輔助函數的名稱。 ``` <script src="https://cdnurl.com/somelibrary.js"></script> <script> function myCreateGraph() { // createGraph logic here } function myDrawGraph() { // drawGraph logic here } </script> ``` 當我們使用此解決方案時,我們還將這些函數呼叫更改為新函數名稱。 - 另一種方法是使用**IIFE** 。 ``` <script src="https://cdnurl.com/somelibrary.js"></script> <script> const graphUtility = (function () { function createGraph() { // createGraph logic here } function drawGraph() { // drawGraph logic here } return { createGraph, drawGraph } })(); </script> ``` 在此解決方案中,我們建立一個實用程式變數,它是**IIFE**的結果,它傳回一個包含`createGraph`和`drawGraph`兩個方法的物件。 **IIFE**解決的另一個問題就是這個例子。 ``` var li = document.querySelectorAll('.list-group > li'); for (var i = 0, len = li.length; i < len; i++) { li[i].addEventListener('click', function (e) { console.log(i); }) } ``` 假設我們有一個`ul`元素,其類別為**list-group** ,並且它有 5 個`li`子元素。當我們**點擊**單一`li`元素時,我們希望`console.log` `i`的值。 但我們想要的程式碼中的行為不起作用。相反,它會在對`li`元素的任何**點擊**中記錄`5` 。我們遇到的問題是由於**閉包的**工作方式造成的。**閉包**只是函數記住其當前作用域、其父函數作用域和全域作用域中的變數引用的能力。當我們在全域範圍內使用`var`關鍵字聲明變數時,顯然我們正在建立一個全域變數`i` 。因此,當我們單擊`li`元素時,它會記錄**5** ,因為這是我們稍後在回調函數中引用它時的`i`值。 - 解決這個問題的一種方法是**IIFE** 。 ``` var li = document.querySelectorAll('.list-group > li'); for (var i = 0, len = li.length; i < len; i++) { (function (currentIndex) { li[currentIndex].addEventListener('click', function (e) { console.log(currentIndex); }) })(i); } ``` 這個解決方案之所以有效,是因為**IIFE**為每次迭代建立一個新範圍,並且我們捕獲`i`的值並將其傳遞到`currentIndex`參數中,因此當我們呼叫**IIFE**時,每次迭代的`currentIndex`值都是不同的。 ### 27. `Function.prototype.apply`方法有什麼用? [^](#the-questions "返回問題") `apply`呼叫一個函數,在呼叫時指定`this`或該函數的「所有者」物件。 ``` const details = { message: 'Hello World!' }; function getMessage(){ return this.message; } getMessage.apply(details); // returns 'Hello World!' ``` 這個方法的工作方式類似於`<a href="#28-what-is-the-use-functionprototypecall-method">Function.prototype.call</a>`唯一的差異是我們傳遞參數的方式。在`apply`中,我們將參數作為陣列傳遞。 ``` const person = { name: "Marko Polo" }; function greeting(greetingMessage) { return `${greetingMessage} ${this.name}`; } greeting.apply(person, ['Hello']); // returns "Hello Marko Polo!" ``` ### 28. `Function.prototype.call`方法有什麼用? [^](#the-questions "返回問題")此`call`呼叫一個函數,指定呼叫時該函數的`this`或「擁有者」物件。 ``` const details = { message: 'Hello World!' }; function getMessage(){ return this.message; } getMessage.call(details); // returns 'Hello World!' ``` 這個方法的工作方式類似於`<a href="#27-what-is-the-use-functionprototypeapply-method">Function.prototype.apply</a>`唯一的差異是我們傳遞參數的方式。在`call`中,我們直接傳遞參數,對於每個參數`,`用逗號分隔它們。 ``` const person = { name: "Marko Polo" }; function greeting(greetingMessage) { return `${greetingMessage} ${this.name}`; } greeting.call(person, 'Hello'); // returns "Hello Marko Polo!" ``` ### 29. `Function.prototype.apply`和`Function.prototype.call`有什麼差別? [↑](#the-questions "返回問題") `apply`和`call`之間的唯一區別是我們如何在被呼叫的函數中傳遞**參數**。在`apply`中,我們將參數作為**陣列**傳遞,而在`call`中,我們直接在參數列表中傳遞參數。 ``` const obj1 = { result:0 }; const obj2 = { result:0 }; function reduceAdd(){ let result = 0; for(let i = 0, len = arguments.length; i < len; i++){ result += arguments[i]; } this.result = result; } reduceAdd.apply(obj1, [1, 2, 3, 4, 5]); // returns 15 reduceAdd.call(obj2, 1, 2, 3, 4, 5); // returns 15 ``` ### 30. `Function.prototype.bind`的用法是什麼? [↑](#the-questions "返回問題") `bind`方法傳回一個新*綁定的*函數 到特定的`this`值或“所有者”物件,因此我們可以稍後在程式碼中使用它。 `call` 、 `apply`方法立即呼叫函數,而不是像`bind`方法那樣傳回一個新函數。 ``` import React from 'react'; class MyComponent extends React.Component { constructor(props){ super(props); this.state = { value : "" } this.handleChange = this.handleChange.bind(this); // Binds the "handleChange" method to the "MyComponent" component } handleChange(e){ //do something amazing here } render(){ return ( <> <input type={this.props.type} value={this.state.value} onChange={this.handleChange} /> </> ) } } ``` ### 31.什麼是**函數式程式設計**? **JavaScript**的哪些特性使其成為**函數式語言**的候選者? [^](#the-questions "返回問題")**函數式程式設計**是一種**聲明式**程式設計範式或模式,它介紹如何**使用表達式來**計算值而不改變傳遞給它的參數的函數來建立應用程式。 JavaScript**陣列**具有**map** 、 **filter** 、 **reduce**方法,這些方法是函數式程式設計世界中最著名的函數,因為它們非常有用,而且它們不會改變或改變陣列,這使得這些函數變得**純粹**,並且JavaScript 支援**閉包**和**高階函數**,它們是**函數式程式語言**的一個特徵。 - **map**方法建立一個新陣列,其中包含對陣列中每個元素呼叫提供的回調函數的結果。 ``` const words = ["Functional", "Procedural", "Object-Oriented"]; const wordsLength = words.map(word => word.length); ``` - **filter**方法會建立一個新陣列,其中包含透過回調函數中測試的所有元素。 ``` const data = [ { name: 'Mark', isRegistered: true }, { name: 'Mary', isRegistered: false }, { name: 'Mae', isRegistered: true } ]; const registeredUsers = data.filter(user => user.isRegistered); ``` - **reduce**方法對累加器和陣列中的每個元素(從左到右)套用函數,將其減少為單一值。 ``` const strs = ["I", " ", "am", " ", "Iron", " ", "Man"]; const result = strs.reduce((acc, currentStr) => acc + currentStr, ""); ``` ### 32.什麼是**高階函數**? [^](#the-questions "返回問題")**高階函數**是可以傳回函數或接收具有函數值的一個或多個參數的函數。 ``` function higherOrderFunction(param,callback){ return callback(param); } ``` ### 33.為什麼函數被稱為**First-class Objects** ? [^](#the-questions "返回問題") JavaScript 中的 \_\_Functions\_\_ 是**一流物件**,因為它們被視為該語言中的任何其他值。它們可以分配給**變數**,可以是稱為**方法的物件的屬性**,可以是**陣列中的專案**,可以**作為參數傳遞給函數**,也可以**作為函數的值返回**。函數與**JavaScript**中任何其他值之間的唯一區別是**函數**可以被呼叫。 ### 34. 手動實作`Array.prototype.map`方法。 [↑](#the-questions "返回問題") ``` function map(arr, mapCallback) { // First, we check if the parameters passed are right. if (!Array.isArray(arr) || !arr.length || typeof mapCallback !== 'function') { return []; } else { let result = []; // We're making a results array every time we call this function // because we don't want to mutate the original array. for (let i = 0, len = arr.length; i < len; i++) { result.push(mapCallback(arr[i], i, arr)); // push the result of the mapCallback in the 'result' array } return result; // return the result array } } ``` 正如`Array.prototype.map`方法的MDN描述。 **map() 方法建立一個新陣列,其中包含對呼叫陣列中的每個元素呼叫所提供函數的結果。** ### 35. 手動實作`Array.prototype.filter`方法。 [↑](#the-questions "返回問題") ``` function filter(arr, filterCallback) { // First, we check if the parameters passed are right. if (!Array.isArray(arr) || !arr.length || typeof filterCallback !== 'function') { return []; } else { let result = []; // We're making a results array every time we call this function // because we don't want to mutate the original array. for (let i = 0, len = arr.length; i < len; i++) { // check if the return value of the filterCallback is true or "truthy" if (filterCallback(arr[i], i, arr)) { // push the current item in the 'result' array if the condition is true result.push(arr[i]); } } return result; // return the result array } } ``` 正如`Array.prototype.filter`方法的 MDN 描述。 **filter() 方法建立一個新陣列,其中包含透過所提供函數實現的測試的所有元素。** ### 36. 手動實作`Array.prototype.reduce`方法。 [↑](#the-questions "返回問題") ``js 函數reduce(arr,reduceCallback,initialValue){ // 首先,我們檢查傳遞的參數是否正確。 if (!Array.isArray(arr) || !arr.length || typeof reduceCallback !== 'function') { ``` return []; ``` } 別的 { ``` // If no initialValue has been passed to the function we're gonna use the ``` ``` let hasInitialValue = initialValue !== undefined; ``` ``` let value = hasInitialValue ? initialValue : arr[0]; ``` ``` // first array item as the initialValue ``` ``` // Then we're gonna start looping at index 1 if there is no ``` ``` // initialValue has been passed to the function else we start at 0 if ``` ``` // there is an initialValue. ``` ``` for (let i = hasInitialValue ? 0 : 1, len = arr.length; i < len; i++) { ``` ``` // Then for every iteration we assign the result of the ``` ``` // reduceCallback to the variable value. ``` ``` value = reduceCallback(value, arr[i], i, arr); ``` ``` } ``` ``` return value; ``` } } ``` As the MDN description of the <code>Array.prototype.reduce</code> method. __The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.__ ###37. What is the __arguments__ object? [&uarr;](#the-questions "Back To Questions") The __arguments__ object is a collection of parameter values pass in a function. It's an __Array-like__ object because it has a __length__ property and we can access individual values using array indexing notation <code>arguments[1]</code> but it does not have the built-in methods in an array <code>forEach</code>,<code>reduce</code>,<code>filter</code> and <code>map</code>. It helps us know the number of arguments pass in a function. We can convert the <code>arguments</code> object into an array using the <code>Array.prototype.slice</code>. ``` 函數一(){ 返回 Array.prototype.slice.call(參數); } ``` Note: __the <code>arguments</code> object does not work on ES6 arrow functions.__ ``` 函數一(){ 返回參數; } 常數二 = 函數 () { 返回參數; } 常量三 = 函數三() { 返回參數; } const 四 = () =&gt; 參數; 四(); // 拋出錯誤 - 參數未定義 ``` When we invoke the function <code>four</code> it throws a <code>ReferenceError: arguments is not defined</code> error. We can solve this problem if your enviroment supports the __rest syntax__. ``` const 四 = (...args) =&gt; args; ``` This puts all parameter values in an array automatically. ###38. How to create an object without a __prototype__? [&uarr;](#the-questions "Back To Questions") We can create an object without a _prototype_ using the <code>Object.create</code> method. ``` 常數 o1 = {}; console.log(o1.toString()); // Logs \[object Object\] 取得此方法到Object.prototype const o2 = Object.create(null); // 第一個參數是物件「o2」的原型,在此 // case 將為 null 指定我們不需要任何原型 console.log(o2.toString()); // 拋出錯誤 o2.toString 不是函數 ``` ###39. Why does <code>b</code> in this code become a global variable when you call this function? [&uarr;](#the-questions "Back To Questions") ``` 函數 myFunc() { 令a = b = 0; } myFunc(); ``` The reason for this is that __assignment operator__ or __=__ has right-to-left __associativity__ or __evaluation__. What this means is that when multiple assignment operators appear in a single expression they evaluated from right to left. So our code becomes likes this. ``` 函數 myFunc() { 令 a = (b = 0); } myFunc(); ``` First, the expression <code>b = 0</code> evaluated and in this example <code>b</code> is not declared. So, The JS Engine makes a global variable <code>b</code> outside this function after that the return value of the expression <code>b = 0</code> would be 0 and it's assigned to the new local variable <code>a</code> with a <code>let</code> keyword. We can solve this problem by declaring the variables first before assigning them with value. ``` 函數 myFunc() { 令 a,b; a = b = 0; } myFunc(); ``` ###40. <div id="ecmascript">What is __ECMAScript__</div>? [&uarr;](#the-questions "Back To Questions") __ECMAScript__ is a standard for making scripting languages which means that __JavaScript__ follows the specification changes in __ECMAScript__ standard because it is the __blueprint__ of __JavaScript__. ###41. What are the new features in __ES6__ or __ECMAScript 2015__? [&uarr;](#the-questions "Back To Questions") * [Arrow Functions](#43-what-are-arrow-functions) * [Classes](#44-what-are-classes) * [Template Strings](#45-what-are-template-literals) * __Enhanced Object literals__ * [Object Destructuring](#46-what-is-object-destructuring) * [Promises](#50-what-are-promises) * __Generators__ * [Modules](#47-what-are-es6-modules) * Symbol * __Proxies__ * [Sets](#48-what-is-the-set-object-and-how-does-it-work) * [Default Function parameters](#53-what-are-default-parameters) * [Rest and Spread](#52-whats-the-difference-between-spread-operator-and-rest-operator) * [Block Scoping with <code>let</code> and <code>const</code>](#42-whats-the-difference-between-var-let-and-const-keywords) ###42. What's the difference between <code>var</code>, <code>let</code> and <code>const</code> keywords? [&uarr;](#the-questions "Back To Questions") Variables declared with <code>var</code> keyword are _function scoped_. What this means that variables can be accessed across that function even if we declare that variable inside a block. ``` 函數給MeX(showX) { 如果(顯示X){ ``` var x = 5; ``` } 返回x; } console.log(giveMeX(false)); console.log(giveMeX(true)); ``` The first <code>console.log</code> statement logs <code>undefined</code> and the second <code>5</code>. We can access the <code>x</code> variable due to the reason that it gets _hoisted_ at the top of the function scope. So our function code is intepreted like this. ``` 函數給MeX(showX) { 變數 x; // 有一個預設值未定義 如果(顯示X){ ``` x = 5; ``` } 返回x; } ``` If you are wondering why it logs <code>undefined</code> in the first <code>console.log</code> statement remember variables declared without an initial value has a default value of <code>undefined</code>. Variables declared with <code>let</code> and <code>const</code> keyword are _block scoped_. What this means that variable can only be accessed on that block <code>{}</code> on where we declare it. ``` 函數給MeX(showX) { 如果(顯示X){ ``` let x = 5; ``` } 返回x; } 函數給MeY(顯示Y){ 如果(顯示Y){ ``` let y = 5; ``` } 返回y; } ``` If we call this functions with an argument of <code>false</code> it throws a <code>Reference Error</code> because we can't access the <code>x</code> and <code>y</code> variables outside that block and those variables are not _hoisted_. There is also a difference between <code>let</code> and <code>const</code> we can assign new values using <code>let</code> but we can't in <code>const</code> but <code>const</code> are mutable meaning. What this means is if the value that we assign to a <code>const</code> is an object we can change the values of those properties but can't reassign a new value to that variable. ###43. What are __Arrow functions__? [&uarr;](#the-questions "Back To Questions") __Arrow Functions__ are a new way of making functions in JavaScript. __Arrow Functions__ takes a little time in making functions and has a cleaner syntax than a __function expression__ because we omit the <code>function</code> keyword in making them. ``` //ES5版本 var getCurrentDate = 函數 (){ 返回新日期(); } //ES6版本 const getCurrentDate = () =&gt; new Date(); ``` In this example, in the ES5 Version have <code>function(){}</code> declaration and <code>return</code> keyword needed to make a function and return a value respectively. In the __Arrow Function__ version we only need the <code>()</code> parentheses and we don't need a <code>return</code> statement because __Arrow Functions__ have a implicit return if we have only one expression or value to return. ``` //ES5版本 函數問候(名稱){ return '你好' + 名字 + '!'; } //ES6版本 const 問候 = (name) =&gt; `Hello ${name}` ; constgreet2 = 名稱 =&gt; `Hello ${name}` ; ``` We can also parameters in __Arrow functions__ the same as the __function expressions__ and __function declarations__. If we have one parameter in an __Arrow Function__ we can omit the parentheses it is also valid. ``` const getArgs = () =&gt; 參數 const getArgs2 = (...休息) =&gt; 休息 ``` __Arrow functions__ don't have access to the <code>arguments</code> object. So calling the first <code>getArgs</code> func will throw an Error. Instead we can use the __rest parameters__ to get all the arguments passed in an arrow function. ``` 常量資料 = { 結果:0, 數字:\[1,2,3,4,5\], 計算結果() { ``` // "this" here refers to the "data" object ``` ``` const addAll = () => { ``` ``` // arrow functions "copies" the "this" value of ``` ``` // the lexical enclosing function ``` ``` return this.nums.reduce((total, cur) => total + cur, 0) ``` ``` }; ``` ``` this.result = addAll(); ``` } }; ``` __Arrow functions__ don't have their own <code>this</code> value. It captures or gets the <code>this</code> value of lexically enclosing function or in this example, the <code>addAll</code> function copies the <code>this</code> value of the <code>computeResult</code> method and if we declare an arrow function in the global scope the value of <code>this</code> would be the <code>window</code> object. ###44. What are __Classes__? [&uarr;](#the-questions "Back To Questions") __Classes__ is the new way of writing _constructor functions_ in __JavaScript__. It is _syntactic sugar_ for using _constructor functions_, it still uses __prototypes__ and __Prototype-Based Inheritance__ under the hood. ``` //ES5版本 函數人(名字,姓氏,年齡,地址){ ``` this.firstName = firstName; ``` ``` this.lastName = lastName; ``` ``` this.age = age; ``` ``` this.address = address; ``` } Person.self = 函數(){ ``` return this; ``` } Person.prototype.toString = function(){ ``` return "[object Person]"; ``` } Person.prototype.getFullName = function (){ ``` return this.firstName + " " + this.lastName; ``` } //ES6版本 類人{ ``` constructor(firstName, lastName, age, address){ ``` ``` this.lastName = lastName; ``` ``` this.firstName = firstName; ``` ``` this.age = age; ``` ``` this.address = address; ``` ``` } ``` ``` static self() { ``` ``` return this; ``` ``` } ``` ``` toString(){ ``` ``` return "[object Person]"; ``` ``` } ``` ``` getFullName(){ ``` ``` return `${this.firstName} ${this.lastName}`; ``` ``` } ``` } ``` __Overriding Methods__ and __Inheriting from another class__. ``` //ES5版本 Employee.prototype = Object.create(Person.prototype); 函數 Employee(名字, 姓氏, 年齡, 地址, 職位名稱, 開始年份) { Person.call(this, 名字, 姓氏, 年齡, 地址); this.jobTitle = jobTitle; this.yearStarted = YearStarted; } Employee.prototype.describe = function () { return `I am ${this.getFullName()} and I have a position of ${this.jobTitle} and I started at ${this.yearStarted}` ; } Employee.prototype.toString = function () { 返回“\[物件員工\]”; } //ES6版本 class Employee extends Person { //繼承自「Person」類 建構函數(名字,姓氏,年齡,地址,工作標題,開始年份){ ``` super(firstName, lastName, age, address); ``` ``` this.jobTitle = jobTitle; ``` ``` this.yearStarted = yearStarted; ``` } 描述() { ``` return `I am ${this.getFullName()} and I have a position of ${this.jobTitle} and I started at ${this.yearStarted}`; ``` } toString() { // 重寫「Person」的「toString」方法 ``` return "[object Employee]"; ``` } } ``` So how do we know that it uses _prototypes_ under the hood? ``` 類別東西{ } 函數 AnotherSomething(){ } const as = new AnotherSomething(); const s = new Something(); console.log(typeof Something); // 記錄“函數” console.log(AnotherSomething 類型); // 記錄“函數” console.log(as.toString()); // 記錄“\[物件物件\]” console.log(as.toString()); // 記錄“\[物件物件\]” console.log(as.toString === Object.prototype.toString); console.log(s.toString === Object.prototype.toString); // 兩個日誌都回傳 true 表示我們仍在使用 // 底層原型,因為 Object.prototype 是 // 原型鏈的最後一部分和“Something” // 和「AnotherSomething」都繼承自Object.prototype ``` ###45. What are __Template Literals__? [&uarr;](#the-questions "Back To Questions") __Template Literals__ are a new way of making __strings__ in JavaScript. We can make __Template Literal__ by using the backtick or back-quote symbol. ``` //ES5版本 vargreet = '嗨,我是馬克'; //ES6版本 讓問候 = `Hi I'm Mark` ; ``` In the ES5 version, we need to escape the <code>'</code> using the <code>\\</code> to _escape_ the normal functionality of that symbol which in this case is to finish that string value. In Template Literals, we don't need to do that. ``` //ES5版本 var 最後一個字 = '\\n' - ' 在' - '我\\n' - '鋼鐵人\\n'; //ES6版本 讓最後一個單字=` ``` I ``` ``` Am ``` 鋼鐵人 `; ``` In the ES5 version, we need to add this <code>\n</code> to have a new line in our string. In Template Literals, we don't need to do that. ``` //ES5版本 函數問候(名稱){ return '你好' + 名字 + '!'; } //ES6版本 const 問候 = 名稱 =&gt; { 返回`Hello ${name} !` ; } ``` In the ES5 version, If we need to add an expression or value in a string we need to use the <code>+</code> or string concatenation operator. In Template Literals, we can embed an expression using <code>${expr}</code> which makes it cleaner than the ES5 version. ###46. What is __Object Destructuring__? [&uarr;](#the-questions "Back To Questions") __Object Destructuring__ is a new and cleaner way of __getting__ or __extracting__ values from an object or an array. Suppose we have an object that looks like this. ``` 常量僱員 = { 名字:“馬可”, 姓氏:“波羅”, 職位:“軟體開發人員”, 聘用年份:2017 }; ``` The old way of getting properties from an object is we make a variable t

高階端對端 DevOps 專案:使用 Terraform、Helm、Jenkins 和 ArgoCD 將微服務應用程式部署到 AWS EKS(第一部分)

DevOps 是 IT 產業中一個快速發展的領域。作為一名 DevOps 工程師,跟上開發空間以避免落後至關重要。 GitOPs 是該領域已經發展成熟的流行範例。 **GitOps**是一種 DevOps 框架或實踐,透過它,我們使 Git 儲存庫成為單一事實來源,同時將 CI/CD 和版本控制應用於基礎設施自動化。 [紅帽](https://www.redhat.com/en/topics/devops/what-is-gitops)將其定義為「使用 Git 儲存庫作為單一事實來源來交付基礎設施即程式碼」。 另一方面, **[DevSecOps](https://aws.amazon.com/what-is/devsecops/#:~:text=DevSecOps%20is%20the%20practice%20of,is%20both%20efficient%20and%20secure.)**是 DevOps 的新改進版本,它在 SDLC(軟體開發生命週期)中灌輸安全工具和控制措施。 devsecops 方法的主要目標是“將安全性左移”,即安全性應該從一開始就成為開發生命週期的一部分,而不是事後才想到。 在本專案指南中,我們將應用 GitOps 實踐,同時實作包含許多工具的高階端對端 DevSecOps 管道。 專案概況 ==== 這是一個由兩部分組成的專案。在第一部分中,我們將設定執行 CI 管道的 EC2 執行個體。 **若要了解如何使用 jenkins 建立標準的持續整合管道,請按[此處](https://dev.to/kelvinskell/a-practical-guide-to-building-a-standard-continuous-integration-pipeline-with-jenkins-2kp9)。** 在第二部分中,我們將設定 EKS 叢集、ArgoCD 用於持續交付,並配置 Prometheus 和 Grafana 用於應用程式監控。 在這個專案中,我們將涵蓋以下內容: **- 基礎架構即程式碼:**我們將使用 terraform 來設定我們的 EC2 執行個體以及 EKS 叢集。 **- Jenkins 伺服器設定:**在 Jenkins 伺服器上安裝和設定基本工具,包括 Jenkins 本身、Docker、OWASP 相依性檢查、Sonarqube 和 Trivy。 **- EKS 叢集部署:**利用 Terraform 建立 Amazon EKS 叢集,這是 AWS 上的託管 Kubernetes 服務。 **- 負載平衡器配置:**為 EKS 叢集配置 AWS 應用程式負載平衡器 (ALB)。 **- ArgoCD 安裝:**安裝並設定 ArgoCD 以實現持續交付和 GitOps。 **- Sonarqube 整合:**整合 Sonarqube 以在 DevSecOps 管道中進行程式碼品質分析。 **- 監控設定:**使用 Helm、Prometheus 和 Grafana 實現對 EKS 叢集的監控。 **- ArgoCD應用程式部署:**使用ArgoCD部署微服務應用程式,包括資料庫和入口元件。 第一部分:設定 CI 管道 ============= **- 第 1 步:設定 EC2 執行個體** 克隆[Git 儲存庫](https://github.com/Kelvinskell/microservices-devops-1)。 `cd`進入 terraform 目錄。 執行`terraform init` ,然後執行`terraform plan`以查看建議的基礎架構變更。 執行`terraform apply`來實作這些變更並配置實例。 此實例使用使用者資料進行引導,一旦配置完畢,將自動安裝 jenkins、sonarqube、trivy 和 docker。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7bpfkke1mp7k5xnvdhjw.png) **- 步驟2:修改應用程式程式碼** 這是一個簡單但關鍵的步驟。在您剛剛複製的儲存庫中包含的**Jenkinsfile**中,您必須將所有出現的「 **kelvinskell** 」變更為您的 DockerHub 使用者名稱。如果您想自己實施這個專案,這是非常有必要的。 **- 第 3 步:設定 Jenkins 伺服器** - 在瀏覽器上登入jenkins伺服器。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cryly0tf1nzxwbdlha9o.png) - 安裝建議的插件並完成註冊。 - 前往“管理Jenkins”、“插件”,然後安裝以下插件:Docker、Docker Commons、Docker pipeline、SonarQube Scanner、Sonar 品質門、SSH2 Easy、OWASP 依賴項檢查、OWASP Markup Formatter 插件、GitHub API pluin 和GitHub pipeline插件。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r12a2xjz5p9svyii685e.png) - 設定工具:前往 Dashborad > 管理 jenkins > 工具 **git安裝** ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qvhas5tzgkmdbokqkz2a.png) **聲納掃描器安裝** ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oil2k0fymyutyttuqljn.png) **依賴性檢查** ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8xvuiz5hxndem72wce9j.png) **Docker安裝** ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6dgt502xm5qxpmgpeof5.png) **- 第 4 步:配置 SonarQube** - 在瀏覽器上,連接到連接埠 9000 上的 Jenkins 伺服器 IP 位址並登入伺服器。 預設使用者名稱和密碼是“admin”。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v6f84jf2phosumnfnt4v.png) 登入後,按一下“手動”。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dz4r3d83eitw5hbyb0x8.png) 請按照上圖中的說明操作,然後按一下「設定」。 **注意:**您的專案金鑰必須完全是**newsread-microservices-application** 。這樣,您就不必編輯 Jenkinsfile。 - 選擇**“With Jenkins”**並選擇 GitHub 作為 DevOps 平台。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4bnnbea6j43tvj0h3ljw.png) - 點擊**“配置分析”** ,在步驟3中,複製“sonar.projectKey”,稍後您將需要它。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wdcus7h1uzotllmnnuq6.png) - 點選「帳戶」>「我的帳戶」>「產生令牌」。 為其命名並點擊“生成”。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0tz5qe7ooadml77g0cu4.png) - 前往“管理 Jenkins”>“憑證” - 選擇 Secret tex 並貼上您剛剛複製的令牌。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cz59t3tbuhckci2fxgt0.png) - 現在前往 Jenkins 儀表板 > 設定 Jenkins > 系統 > Sonarqube 伺服器 > 新增 Sonarqube - 將其命名為“SonarQube Server”,輸入秘密令牌的伺服器 URL 和憑證 ID。 請注意,我們的伺服器 url 是 localhost,因為 SonarQube 與 jenkins 託管在同一台伺服器上。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2a770dmbbjbbbg66pbft.png) - 點選“儲存”。 **- 第 5 步:整合您的 DockerHub 憑證** 此階段對於 Jenkins 存取您的 DockerHub 帳戶至關重要。 - 前往“管理 Jenkins”>“憑證”>“新增憑證” ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0oi45zq6c0wmtl08u53v.png) **- 第 6 步:設定 Jenkins 管道** - 從 Jenkins 的儀表板中,按一下「新專案」並建立管道作業。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wxwu61m452794k2crxqp.png) - 在“建置觸發器”下,選擇“觸發遠端建置”。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gqu6svazhn7zjyotm9yk.png) 在「身份驗證令牌」方塊下設定秘密令牌。我們將在建立 GitHub Webhook 時使用它。 - 在管道下,確保參數設定如下: - 定義:來自 SCM 的管道腳本 - SCM:設定您的 SCM。確保只建立您的主分支。例如,如果您的主分支名為“main”,請將“\*/main”放在要建置的分支下。 - 腳本路徑:Jenkinsfile ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sqy8e5uicfpwm523701p.png) **注意:**您必須將我的[儲存庫](https://github.com/Kelvinskell/microservices-devops-1)分叉到您自己的 GitHub 帳戶。這是您存取儲存庫並能夠對其進行配置所必需的。 完成此操作後,建立 GitHub 個人存取權杖。 我們將使用 GitHub PAT 從 Jenkins 向我們的儲存庫進行身份驗證。 - 連接到 EC2 實例,切換到 jenkins 用戶,建立 SSH 金鑰對。公鑰將作為您的 PAT 上傳到 GitHub,而私鑰將加入到我們的 Jenkins 配置中。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2dy0fk403lqv50eeh1nd.png) - 返回 Jenkins 伺服器,點擊“新增憑證” ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b9t7mfdbdun64k7n80m6.png) 錯誤訊息現已消失。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8cwoepv5sgkzaq16u5f4.png) - 點選“儲存”。 **- 第 7 步:建立 GitHub WebHook** 這對於遠端觸發我們的詹金斯建置是必要的。 - 前往儲存庫的 GitHub Webhook 建立頁面並輸入以下資訊: URL:輸入以下 URL,根據需要替換 \*\*\* 之間的值: ``` ***JENKINS_SERVER_URL***/job/***JENKINS_JOB_NAME***/build?token=***JENKINS_BUILD_TRIGGER_TOKEN*** ``` ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0qb14f6bp78i03f2jbs9.png) **- 第 8 步:執行管道** 現在,我們已經完成了該管道的配置。是時候檢驗我們的工作了。 您可以透過進行變更並推送到 GitHub 儲存庫來觸發管道。如果正確配置了 Web hook 觸發器,這將自動啟動管道。 或者,您只需點擊“立即建置”即可執行管道。 如果一切都按預期配置,您將得到以下輸出: ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kzesc1d3m2wtebg5z9al.png) 結論 -- 我們現在已經結束了這個專案的第一部分。在第一部分中,我們配置並設定了持續整合管道。第二部分將涉及使用 ArgoCD 實施 GitOps。 我們將使用 terraform 配置 EKS 集群,然後使用 ArgoCD 持續部署到 EKS 集群。 這裡的想法是,您可以讓單獨的團隊管理流程的兩個部分 - 持續整合和持續部署。從而進一步解耦和簡化整個過程,同時使用 Git 作為我們的單一事實來源。 **PS:**我願意接受遠距 DevOps、雲端和科技寫作機會。 在[LinkedIn](https://linkedin.com/in/kelvin-onuchukwu-3460871a1)上與我聯絡。 --- 原文出處:https://dev.to/kelvinskell/advanced-end-to-end-devops-project-deploying-a-microservices-app-to-aws-eks-using-terraform-helm-jenkins-and-argocd-part-i-3a53

CSS 行高的工作原理和最佳實踐

CSS 屬性`line-height`定義兩個內嵌元素之間的間距。典型用途是分隔文字。您可以看到人們將其與“前導”進行比較,“前導”是印刷術中使用的術語,指兩行文本的基線之間的空間。 `line-height`工作方式不同。它在文字上方和下方加入了空間。 ![行距與行高](https://thepracticaldev.s3.amazonaws.com/i/lsrnzx1hin6mkqg6fagw.png) 左:行距,右:行高 用法 -- 您可以使用具有不同值的`line-height`如下所示: ``` body { line-height: normal; /* default */ line-height: 2; line-height: 1em; line-height: 1rem; line-height: 200%; line-height: 20px; } ``` 噢,孩子😧!好多啊。讓我們一一分析一下👍。 ### 預設值和無單位值 如果您不將其設定為不同的值,則「正常」是預設值。通常,這意味著它設定為`1.2` ,這取決於瀏覽器供應商。那麼只有一個數字值而沒有任何單位是什麼意思呢?它實際上是一個乘數。它採用`font-size`值並將其乘以`1.2` 。讓我們用下面的例子來計算一條線的高度。 ``` body { font-size: 16px; line-height: 1.5; } ``` 我們只需要做以下計算:16 \* 1.5 = 24px。現在我們知道文字的最小高度為 24 像素。因此它將在文字下方和上方加入 4 個像素。酷就這麼簡單😎! ### em 和 rem 下一個是`em`和`rem` 。 `rem`相對於根元素的`font-size` , `em`相對於目前元素的 font-size。這是一個例子 ``` html { font-size: 12px; } .remExample { font-size: 16px; line-height: 1.5rem; /* line-height will be 12 * 1.5 = 18px */ } .emExample { font-size: 16px; line-height: 1.5em; /* line-height will be 16 * 1.5 = 24px */ } ``` ### 百分比 `%`值有點難以閱讀。 100%意味著乘以1。再次舉例來說明這一點。 ``` body { font-size: 12px; } .percentage { font-size: 16px; line-height: 150%; /* line-height will be 16 * 1.5 = 24px */ } ``` ### 像素(px) 對我來說最簡單也是最令人困惑的是`px`值。將其設為任何像素值都會將其精確地設定為該值。因此,如果您的`font-size`為 16px,並且您將`line-height`設為 12px,您的字體將比它所包裝的容器更大。一般來說,您應該盡量避免在行高中使用`px`值! ``` body { font-size: 16px; } .pixel { line-height: 12px; } ``` ### 一些最佳實踐 一般來說,我先將`body`元素中的`font-size`和`line-height`設定為以下值。 ``` body { font-size: 16px; line-height: 1.5; } ``` 由此,您可以建立所有其他樣式。我會盡量避免使用無單位數字以外的任何東西。另外,嘗試使用易於分割的`font-size`值,例如 16 或 12。這將有助於您在設計中保持平衡。您也可以在`margin`和`padding`中使用它。在腦中計算 16 \* 1.5 比 13 \* 1.5 更容易。然後您將永遠知道實際價值是多少。 ``` body { font-size: 16px; line-height: 1.5; } h1, h2, h3, h4, ul, ol { margin-bottom: 15rem; } button { display: inline-block; padding: 0.75rem 1.5rem; } ``` 當然,你可以嘗試一下,這些規則也會有例外,但我總是這樣開始。 資源 -- - http://www.indesignskills.com/tutorials/leading-typography/ - https://developer.mozilla.org/en-US/docs/Web/CSS/line-height - https://www.w3schools.com/cssref/pr\_dim\_line-height.asp - https://css-tricks.com/almanac/properties/l/line-height/ - https://ux.stackexchange.com/questions/35270/is-there-an-optimal-font-size-line-height-ratio **謝謝閱讀!** --- 原文出處:https://dev.to/lampewebdev/css-line-height-jjp

開源 SaaS:您無需為 SaaS 模板付費

展示開放 SaaS 🎉 ----------- 我們非常高興推出[Open SaaS](https://opensaas.sh) ,這是適用於 React、NodeJS 和 Prisma 的完全免費、開源、生產級 SaaS 樣板。 在這裡查看它的實際效果: https://www.youtube.com/watch?v=rfO5SbLfyFE Open SaaS 擁有您最近看到的那些付費 SaaS 入門者的所有功能,除了它完全**免費**且**開源**。 **我們覺得為一些需要自己管理的樣板程式碼支付 300-2,000 美元是瘋狂的**。最重要的是,許多樣板文件嚴重依賴第三方服務。再加上託管和其他費用,您需要花費大量資金才能將您的想法推向世界。 **這就是為什麼透過開放 SaaS,我們有意識地決定盡可能嘗試使用開源和免費服務。**例如,我們在[OpenSaaS.sh](http://OpenSaaS.sh)上託管的演示應用程式及其管理儀表板由 Plausible 分析的自架版本提供支援。希望您的 SaaS 具有相同的功能嗎?那麼,Open SaaS 已為您預先配置好! 此外,Open SaaS 使用的[Wasp 框架](https://wasp.sh)可以為您建立許多功能,例如 Auth 和 Cron 作業,這樣您就不必支付第三方服務費用或完全自己編寫程式碼(我們稍後會更詳細地解釋這一點)。 在我們開始之前... ---------- 悠悠悠悠👋 [![開放 SaaS - 開源且 100% 免費的 React 和 Node.js SaaS 初學者! |產品搜尋](https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=436467&theme=light)](https://www.producthunt.com/posts/open-saas?utm_source=badge-featured&utm_medium=badge&utm_souce=badge-open-saas) Open SaaS[現已在 Product Hunt](https://www.producthunt.com/posts/open-saas)上線!快來支持我們的免費開源倡議🙏 [![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wppn8mlby0p7h1f8xl6w.png)](https://www.producthunt.com/posts/open-saas) 為什麼我們要建造它......然後免費贈送它 ---------------------- [我們預發布版本](https://devhunt.org/tool/open-saas)中的初步回饋基本上是正面的,但我們也收到了一些問題,例如: - “它會保持免費嗎?” - “您開源這個的動機是什麼?” 所以我們認為我們應該先回答這些問題。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5rac9o1rxgrwfx51mc50.png) 首先,是的,它是 100% 免費和開源的,並將保持這種狀態。 其次,我們相信,開發者、獨立駭客和個人企業家社群的集體知識將比個人或小團體產生更好的樣板。當您從某些開發人員那裡購買SaaS 入門版時,您已經獲得了一個固執己見的堆棧,然後除此之外,您還獲得了按照他們認為最好的方式建置的應用程式- 這可能並不總是最適合*您。* 第三, [Open SaaS](https://opensaas.sh)是[Wasp](https://wasp.sh)的一個專案,一個超強的開源React + NodeJS + Prisma全端框架。我們 Wasp 團隊相信 Wasp 非常適合快速且有效率地建立 SaaS 應用程式,我們希望這個模板能夠證明這一點。另外,身為開發人員,我們從其他開源專案中學到了很多東西,而 Wasp 本身就是一個開源專案。 基本上,我們熱愛開源理念,並且希望將其發揚光大。 🙏 因此,我們希望能夠為開發者社群提供非常有價值的資產,同時宣傳我們的開源全端框架。我們很高興看到社區為其做出貢獻,以便它不斷發展並成為最好的 SaaS 樣板。 開放 SaaS 是由什麼組成的 --------------- 我們在 Open SaaS 上投入了大量的精力,包括[文件](https://docs.opensaas.sh),以便開發人員可以自信、輕鬆地啟動 SaaS 應用程式。 我們還花了一些時間檢查其他免費的開源 SaaS 啟動器,並希望確保 Open SaaS 具有可立即投入生產的啟動器的所有正確功能,而不顯得臃腫。我們認為我們已經在很大程度上實現了這一點,儘管我們將繼續加入功能並隨著時間的推移進行改進。 目前的主要特點如下: - 🔐 身份驗證(電子郵件驗證、Google、github) - 📩 電子郵件(sendgrid、emailgun、SMTP) - 📈 管理儀表板(合理或谷歌分析) - 🤑 Stripe 付款(只需加入您的訂閱產品 ID) - ⌨️ 端對端類型安全性(無需配置) - 🤖 OpenAI 整合(AI 驅動的範例應用程式) - 📖 Astro 博客 - 🚀 部署在任何地方 - 📄 完整的文件和社群支持 值得深入了解其中每個功能的細節,所以讓我們開始吧。 ### 授權 [![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wbistoghxrxft9zxxra1.png)](https://www.producthunt.com/posts/open-saas) 感謝 Wasp,Open SaaS 附帶了許多可能的身份驗證方法: - 使用者名稱和密碼(最簡單/最容易進行開發測試) - 已驗證電子郵件並重設密碼 - Google 和/或 Github 社群登入 這就是 Wasp 真正發揮作用的地方,因為設定全端 Auth 並取得預先配置的 UI 元件所需要做的就是: ``` //main.wasp app SaaSTemplate { auth: { userEntity: User, methods: { usernameAndPassword: {}, google: {}, gitHub: {}, } } } ``` 嚴重地。就是這樣! 只需確保您已設定社交身份驗證並擁有 API 金鑰以及定義的`User`和`ExternalAuth`實體,就可以開始了。不用擔心,這部分內容已在[Open SaaS Docs](https://docs.opensaas.sh)中詳細記錄和解釋。 最重要的是,Open SaaS 預先配置了一些範例,說明如何自訂和建立一些真正強大的身份驗證流程。 ### 管理儀表板和分析 [![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4mm6s1c3txxgm49e2k7w.png)](https://www.producthunt.com/posts/open-saas) 透過利用[Wasp 的工作功能](https://wasp-lang.dev/docs/advanced/jobs),Open SaaS 每小時從 Plausible 或 Google 的網站分析(您的選擇!)和 Stripe 的資料 API 中提取資料,並將其保存到我們的資料庫中。然後,該資料將顯示在我們的管理儀表板上(前往[OpenSaaS.sh](https://OpenSaaS.sh)查看其實際情況)。好的部分是,要為您自己的應用程式存取這些資料,您所要做的就是按照我們的指南獲取分析 API 金鑰,插入提供的腳本,然後就可以開始了! 再次強調,Wasp 讓整個過程變得非常簡單。透過已經為您定義的查詢 API 和取得我們需要的資料的功能,Open SaaS 然後在`main.wasp`設定檔中使用 Wasp 作業: ``` job dailyStatsJob { executor: PgBoss, perform: { fn: import { calculateDailyStats } from "@server/workers/calculateDailyStats.js" }, schedule: { cron: "0 * * * *" }, entities: [User, DailyStats, Logs, PageViewSource] } ``` 就是這樣! Wasp 負責為您設定和執行 cron 作業。 ### 條紋支付 [![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ugy3mx9xo1d9i9vfysr7.png)](https://www.producthunt.com/posts/open-saas) 如果您是以前從未建立過自己的 SaaS 的開發人員,那麼與 Stripe 這樣的支付處理器整合可能是您將面臨的少數挑戰之一。 當我建立第一個 SaaS [CoverLetterGPT.xyz](https://coverlettergpt.xyz)時,我的情況就是如此。這實際上是我建造它的主要動機之一;了解如何將 Stripe 支付整合到應用程式以及 OpenAI API 中。 儘管 Stripe 因擁有豐富的文件而聞名,但這個過程仍然令人畏懼。你必須: - 建立正確的產品類型 - 設定 webhook 端點 - 告訴 Stripe 將正確的 Webhook 事件傳送給您 - 正確使用事件 - 處理重複付款和失敗付款 - 在上線之前透過 CLI 進行正確測試 這就是為什麼為您設定 Stripe 訂閱付款是一個巨大的勝利。 但比這更重要的是,為您方便地記錄整個過程!這就是為什麼 Open SaaS[在我們的文件中為您提供方便的 Stripe 指南](https://docs.opensaas.sh)🙂 [![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uehwot350u3dl02s4w7r.png)](https://www.producthunt.com/posts/open-saas) ### 端對端類型安全 Open SaaS 是使用 Typescript 建置的,因為它是一個全棧應用程式,所以從後端到前端的類型安全可以成為真正的救星。我的意思是,一些[固執己見的堆疊](https://create.t3.gg/)在此基礎上變得非常流行。 幸運的是,Wasp 為您提供開箱即用的端到端類型安全性(無需配置!),因此 Open SaaS 可以輕鬆利用它。 這是一個例子: 1. 讓 Wasp 了解您的伺服器操作: ``` // main.wasp action getResponse { fn: import { getResponse } from "@server/actions.js", entities: [Response] } ``` 2. 輸入並實施您的伺服器操作。 ``` // src/srever/actions.ts type RespArgs = { hours: string; }; const getResponse: GetResponse<RespArgs, string> = async ({ hours }) => { } ``` 3. 導入並在客戶端呼叫。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0fah81r1g4bg3vdqapju.png) 客戶端類型將被正確推斷! ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7n04yh6de9slhhnjrgf3.png) ### AI 驅動的範例應用程式(附有 OpenAI API) [![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zbbc2gkxbxjl3q2y01a3.png)](https://www.producthunt.com/posts/open-saas) 人工智慧正在使新的應用程式創意成為可能,這也是我們看到開發人員對建立 SaaS 應用程式的興趣重新抬頭的部分原因。正如我上面提到的,我建造的第一個 SaaS 應用程式[CoverLetterGPT](https://coverlettergpt.xyz)是「GPT 包裝器」之一,我很自豪地說它帶來了約350 美元MRR(每月經常性收入)的可觀被動收入。 我個人認為,我們在軟體開發方面處於最佳狀態,開發新的、有利可圖的人工智慧應用程式有很大的潛力,尤其是「獨立駭客」和「個人企業家」。 這就是 Open SaaS 推出 AI 調度助手演示應用程式的原因。您輸入任務及其分配的時間,AI Scheduler 會為您的一天建立詳細的計劃。 [![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j4suf7g9jm5w93ri3bqx.png)](https://www.producthunt.com/posts/open-saas) 在幕後,這是使用 OpenAI 的 API 為每個任務分配優先級,並將它們分解為詳細的子任務,包括喝咖啡休息時間!它還利用 OpenAI 的函數呼叫功能以使用者定義的 JSON 物件形式回傳回應,以便客戶端每次都能正確使用它。此外,我們計劃在未來加入開源法學碩士,敬請期待! 示範版 AI Scheduler 可協助開發人員學習如何有效使用 OpenAI API,並激發一些 SaaS 應用程式創意! ### 隨處部署。容易地。 許多流行的 SaaS 新創公司都使用依賴託管的框架,這意味著您只能依賴一個提供者進行部署。雖然這些都是簡單的選擇,但它可能並不總是最適合您的應用程式。 Wasp 為您提供了部署全端應用程式的無限可能性: - 使用`wasp deploy`一鍵部署到[Fly.io](http://Fly.io) - 使用`wasp build`並部署 Dockerfiles 和客戶端,無論您喜歡什麼! `wasp deploy`的優點在於它會自動產生和部署您的資料庫、伺服器和用戶端,並為您設定環境變數。 Open SaaS 還內建了環境變數和常數驗證器,以確保您已正確設定部署所需的所有內容,以及文件中的部署指南 [![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fihbij250xtbdtjbjoks.png)](https://www.producthunt.com/posts/open-saas) 最後,您擁有自己的程式碼,並且可以自由地將其部署到任何地方,而無需受供應商鎖定。 幫助我們,幫助你 -------- [![開放 SaaS - 開源且 100% 免費的 React 和 Node.js SaaS 初學者! |產品搜尋](https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=436467&theme=light)](https://www.producthunt.com/posts/open-saas?utm_source=badge-featured&utm_medium=badge&utm_souce=badge-open-saas) 想支持我們的免費開源計畫嗎?那麼現在就去[Product Hunt 上](https://www.producthunt.com/posts/open-saas)向我們提供一些支援吧! 🙏 [![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wppn8mlby0p7h1f8xl6w.png)](https://www.producthunt.com/posts/open-saas) 現在就開始建立您的 SaaS! --------------- 我們希望 Open SaaS 能夠讓更多的開發人員能夠發布他們的想法和副專案。我們也希望從開發人員那裡獲得一些回饋和意見,以便我們能夠使其成為最好的 SaaS 樣板啟動器。 因此,如果您有任何意見或發現任何錯誤,請[在此處提交問題](https://github.com/wasp-lang/open-saas/issues)。 如果您發現 Open SaaS 和/或 Wasp 很有用,最簡單的支援方法就是給我們一顆星: - 為[Open SaaS 儲存庫](https://github.com/wasp-lang/open-saas)加註星標 - 給[黃蜂倉庫](https://github.com/wasp-lang/wasp)加註星標 --- 原文出處:https://dev.to/wasp/you-dont-need-to-pay-for-saas-boilerplates-open-saas-56lj

在沒有伺服器的情況下在視窗之間共享狀態

最近,社群網路上流行一張 gif 動圖,展示了一件 [Bjorn Staal 製作的令人驚嘆的藝術品](https://twitter.com/_nonfigurativ_/status/1727322594570027343)。 ![Bjorn Staal 藝術作品](https://cdn-images-1.medium.com/max/2000/1*vCKb_XLed3eD9y4h-yjdKQ.gif) 我想重新建立它,但缺乏球體、粒子和物理的 3D 技能,我的目標是了解如何讓一個視窗對另一個視窗的位置做出反應。 本質上,在多個視窗之間共享狀態,我發現這是 Bjorn 專案中最酷的方面之一! 由於無法找到有關該主題的好文章或教程,我決定與您分享我的發現。 > 讓我們嘗試根據 Bjorn 的工作建立一個簡化的概念驗證 (POC)! ![我們將嘗試創造什麼(ofc 它比 Bjorn 的作品沒那麼性感)](https://cdn-images-1.medium.com/max/2000/1*KJHO9DmEDcTISWuCcvDpMQ.gif) 我做的第一件事就是列出我所知道的在多個客戶端之間共享資訊的所有方法: ## 呃:伺服器 顯然,擁有伺服器(帶有輪詢或 Websocket)可以簡化問題。然而,由於 Bjorn 在沒有使用伺服器的情況下實現了他的結果,所以這是不可能的。 ## 本機存儲 本地存儲本質上是瀏覽器鍵值存儲,通常用於在瀏覽器會話之間保存資訊。雖然通常用於儲存身份驗證令牌或重定向 URL,但它可以儲存任何可序列化的內容。 [您可以在這裡了解更多](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage)。 我最近發現了一些有趣的本地儲存 API,包括 *`storage`* 事件,每當同一網站的另一個會話更改本地儲存時就會觸發該事件。 ![儲存事件如何運作(當然是簡化的)](https://cdn-images-1.medium.com/max/4048/1*otw7fDvd-XFjj9yVBxn5zg.png) 我們可以透過將每個視窗的狀態儲存在本地儲存中來利用這一點。每當一個視窗改變其狀態時,其他視窗將透過儲存事件進行更新。 這是我最初的想法,這似乎是Bjorn 選擇的解決方案,因為他分享了他的LocalStorage 管理器程式碼以及與ThreeJs 一起使用的範例[此處](https://github.com/bgstaal/multipleWindow3dScene) 。 但是當我發現有程式碼可以解決這個問題時,我想看看是否有其他方法…劇透警告:是的,有! ## 共享工作者 這個華而不實的術語背後是一個令人著迷的概念——WebWorkers 的概念。 簡單來說,工作執行緒本質上是在另一個執行緒上執行的第二個腳本。雖然它們無法存取 DOM(因為它們存在於 HTML 文件之外),但它們仍然可以與您的主腳本進行通訊。 它們主要用於透過處理背景作業來卸載主腳本,例如預取資訊或處理不太關鍵的任務(例如流日誌和輪詢)。 ![腳本與worker之間通訊機制的簡單解釋](https://cdn-images-1.medium.com/max/3548/1*izcnWc_p13m8pZy5d49mVw.png) 共享工作線程是一種特殊類型的 WebWorkers,它可以與同一腳本的多個實例進行通信,這使得它們對我們的用例很有趣!好吧,讓我們直接進入程式碼! ![共享工作人員可以將資訊傳送到同一腳本的多個會話](https://cdn-images-1.medium.com/max/5428/1*A7ObCM2OjojgfFP57ankyw.png) ### 設定工人 如前所述,工作人員是具有自己的入口點的「第二腳本」。根據您的設定(TypeScript、捆綁程式、開發伺服器),您可能需要調整 tsconfig、新增指令或使用特定的匯入語法。 我無法涵蓋所有使用 Web Worker 的可能方法,但您可以在 MDN 或網路上找到資訊。 如果需要,我很樂意為本文撰寫前傳,詳細介紹設定它們的所有方法! 就我而言,我使用的是 Vite 和 TypeScript,因此我需要一個「worker.ts」檔案並將「@types/sharedworker」安裝為開發依賴項。我們可以使用以下語法在主腳本中建立連結: ``` new SharedWorker(new URL("worker.ts", import.meta.url)); ``` 基本上,我們需要: * 辨識每個視窗 * 追蹤所有視窗狀態 * 一旦視窗改變狀態,提醒其他視窗重繪 我們的狀態將非常簡單: ``` type WindowState = { screenX: number; // window.screenX screenY: number; // window.screenY width: number; // window.innerWidth height: number; // window.innerHeight }; ``` 當然,最重要的訊息是“window.screenX”和“window.screenY”,因為它們告訴我們視窗相對於顯示器左上角的位置。 我們將有兩種類型的訊息: * 每個窗口,無論何時改變其狀態,都會發布一個帶有新狀態的“windowStateChangedmessage”。 * 工作人員將向所有其他視窗發送更新,以提醒他們其中一個視窗已更改。工作人員將發送包含所有視窗狀態的「syncmessage」。 我們可以從一個看起來有點像這樣的普通工人開始: ``` // worker.ts let windows: { windowState: WindowState; id: number; port: MessagePort }[] = []; onconnect = ({ ports }) => { const port = ports[0]; port.onmessage = function (event: MessageEvent<WorkerMessage>) { console.log("We'll do something"); }; }; ``` 我們與 SharedWorker 的基本連結如下所示。我有一些基本函數可以產生 id,並計算當前視窗狀態,我還對我們可以使用的稱為 WorkerMessage 的訊息類型進行了一些輸入: ``` // main.ts import { WorkerMessage } from "./types"; import { generateId, getCurrentWindowState, } from "./windowState"; const sharedWorker = new SharedWorker(new URL("worker.ts", import.meta.url)); let currentWindow = getCurrentWindowState(); let id = generateId(); ``` 一旦我們啟動應用程式,我們應該提醒工作人員有一個新窗口,因此我們立即發送一條訊息: ``` // main.ts sharedWorker.port.postMessage({ action: "windowStateChanged", payload: { id, newWindow: currentWindow, }, } satisfies WorkerMessage); ``` 我們可以在工作端監聽此訊息並相應地更改 onmessage。基本上,一旦工作人員收到 windowStateChanged 訊息,要么它是一個新窗口,我們將其附加到狀態,要么它是一個已更改的舊窗口。然後我們應該提醒大家狀態已經改變: ``` // worker.ts port.onmessage = function (event: MessageEvent<WorkerMessage>) { const msg = event.data; switch (msg.action) { case "windowStateChanged": { const { id, newWindow } = msg.payload; const oldWindowIndex = windows.findIndex((w) => w.id === id); if (oldWindowIndex !== -1) { // old one changed windows[oldWindowIndex].windowState = newWindow; } else { // new window windows.push({ id, windowState: newWindow, port }); } windows.forEach((w) => // send sync here ); break; } } }; ``` 為了發送同步,我實際上需要一些技巧,因為“port”屬性無法序列化,所以我將其字串化並解析回來。因為我很懶,所以我不只是將視窗映射到更可序列化的陣列: ``` w.port.postMessage({ action: "sync", payload: { allWindows: JSON.parse(JSON.stringify(windows)) }, } satisfies WorkerMessage); ``` 現在是時候畫東西了! ## 有趣的部分:繪畫! 當然,我們不會做複雜的 3D 球體:我們只會在每個視窗的中心畫一個圓,並在球體之間畫一條線! 我將使用 HTML Canvas 的基本 2D 上下文進行繪製,但您可以使用任何您想要的內容。畫一個圓,非常簡單: ``` const drawCenterCircle = (ctx: CanvasRenderingContext2D, center: Coordinates) => { const { x, y } = center; ctx.strokeStyle = "#eeeeee"; ctx.lineWidth = 10; ctx.beginPath(); ctx.arc(x, y, 100, 0, Math.PI * 2, false); ctx.stroke(); ctx.closePath(); }; ``` 為了繪製線條,我們需要做一些數學運算(我保證,這不是很多🤓),並將另一個視窗中心的相對位置轉換為目前視窗上的座標。 基本上,我們正在改變基地。我用一點數學來做到這一點。首先,我們將更改底座以在顯示器上具有座標,並透過目前視窗 screenX/screenY 進行偏移 ![基本上我們正在尋找鹼基變化後的目標位置](https://cdn-images-1.medium.com/max/5056/1*Zg_z1aZxUE1WP-uOk1owdw.png) ``` const baseChange = ({ currentWindowOffset, targetWindowOffset, targetPosition, }: { currentWindowOffset: Coordinates; targetWindowOffset: Coordinates; targetPosition: Coordinates; }) => { const monitorCoordinate = { x: targetPosition.x + targetWindowOffset.x, y: targetPosition.y + targetWindowOffset.y, }; const currentWindowCoordinate = { x: monitorCoordinate.x - currentWindowOffset.x, y: monitorCoordinate.y - currentWindowOffset.y, }; return currentWindowCoordinate; }; ``` 如您所知,現在我們在同一相對座標系上有兩個點,我們現在可以畫線了! ``` const drawConnectingLine = ({ ctx, hostWindow, targetWindow, }: { ctx: CanvasRenderingContext2D; hostWindow: WindowState; targetWindow: WindowState; }) => { ctx.strokeStyle = "#ff0000"; ctx.lineCap = "round"; const currentWindowOffset: Coordinates = { x: hostWindow.screenX, y: hostWindow.screenY, }; const targetWindowOffset: Coordinates = { x: targetWindow.screenX, y: targetWindow.screenY, }; const origin = getWindowCenter(hostWindow); const target = getWindowCenter(targetWindow); const targetWithBaseChange = baseChange({ currentWindowOffset, targetWindowOffset, targetPosition: target, }); ctx.strokeStyle = "#ff0000"; ctx.lineCap = "round"; ctx.beginPath(); ctx.moveTo(origin.x, origin.y); ctx.lineTo(targetWithBaseChange.x, targetWithBaseChange.y); ctx.stroke(); ctx.closePath(); }; ``` 現在,我們只需要對狀態變化做出反應。 ``` // main.ts sharedWorker.port.onmessage = (event: MessageEvent<WorkerMessage>) => { const msg = event.data; switch (msg.action) { case "sync": { const windows = msg.payload.allWindows; ctx.reset(); drawMainCircle(ctx, center); windows .forEach(({ windowState: targetWindow }) => { drawConnectingLine({ ctx, hostWindow: currentWindow, targetWindow, }); }); } } }; ``` 最後一步,我們只需要定期檢查視窗是否發生變化,如果發生變化則發送訊息 ``` setInterval(() => { const newWindow = getCurrentWindowState(); if ( didWindowChange({ newWindow, oldWindow: currentWindow, }) ) { sharedWorker.port.postMessage({ action: "windowStateChanged", payload: { id, newWindow, }, } satisfies WorkerMessage); currentWindow = newWindow; } }, 100); ``` [您可以在此儲存庫中找到完整的程式碼](https://github.com/achrafl0/multi-window-article)。實際上,我用它做了很多實驗,使它變得更加抽象,但其要點是相同的。 如果您在多個視窗上執行它,希望您能得到與此相同的結果! ![完整結果](https://cdn-images-1.medium.com/max/2000/1*KJHO9DmEDcTISWuCcvDpMQ.gif) 謝謝閱讀 ! 如果您發現這篇文章有幫助、有趣或只是有趣,您可以將其分享給您的朋友/同事/社區 [您也可以訂閱我的電子報](https://notachraf.substack.com/)它是免費的! --- 原文出處:https://dev.to/notachraf/sharing-a-state-between-windows-without-a-serve-23an

幫助我成為技術主管的書籍

## 為什麼是書籍? 在發展我的技能時,我喜歡結合使用會議演講、視訊教學、書籍、論文、部落格文章、邊做邊學和教學/部落格。書籍是從別人所犯的錯誤中學習、從他們的成功中受到啟發以及間接體驗他們的成就的好方法。 在這篇文章中,我想分享我最喜歡的書籍,這些書籍在我從高級軟體工程師到成為技術主管的過程中對我幫助最大。他們幫助我拓寬並加深了對軟體工程、軟體架構以及建構和經營軟體業務的理解。他們教我挑戰和塑造我的行為和習慣。其中一些深深影響了我的個人和職業生活。 不用說,閱讀這些書不會自動讓你升職或讓你擔任新的技術主管職位。當然,你還是需要自己的經驗,自己的錯誤,還需要一點運氣。根據您所從事的特定領域不斷提高您的技術知識和技能也很重要。此清單中的書籍並不關注特定技術,而是適用於任何技術堆疊和業務的一般原則和概念。 對於清單中的每本書,我都會附上一個簡短的摘要,可以幫助您判斷這本書是否與您相關。為了賦予它個人風格,我還將包括我從這本書中學到的最有價值的教訓。這不一定是這本書的主要訊息,也不是唯一重要的訊息,而是最能引起我共鳴的訊息。 ## 列表 ### 設計它! [*Design It!: From Programmer to Software Architect*]((https://www.oreilly.com/library/view/design-it/9781680502923/)) Michael Keeling 是一本針對有志向的軟體開發人員的綜合指南轉變為軟體架構師的角色。本書提供了一種實用且易於理解的軟體架構方法,強調了設計在建立有效的軟體系統中的重要性。 Keeling 涵蓋了廣泛的主題,從軟體架構的基本原理到設計可擴展和可維護系統的實用技術。 在整本書中,基林提倡採用實踐、迭代的軟體設計方法,鼓勵讀者批判性地思考他們所做的架構選擇。他介紹了各種架構風格和模式,並討論如何評估權衡並做出符合專案目標和限制的決策。本書充滿了現實世界的範例、練習和實用技巧,對於那些希望發展軟體架構和設計技能的人來說是一個寶貴的資源。 **我從書中學到的最有價值的教訓:** 不存在「沒有設計」這樣的事情。 「無設計」通常意味著在工程師的腦海中存在多種、隱含的設計,這些設計彼此不一致。明確、協作、迭代地設計,並以書面記錄設計! ### 釋放它! Michael Nygard 的[*Release It!: Design and Deploy Production-Ready Software*](https://www.oreilly.com/library/view/release-it/9781680500264/) 是軟體開發人員和架構師的重要指南討論建立在生產環境中可靠運作的軟體所面臨的挑戰。本書深入探討了設計、部署和維護能夠承受現實世界操作嚴苛的軟體的複雜性。 Nygard 強調從設計過程一開始就考慮生產現實的重要性,並提倡從僅僅編寫程式碼到提供彈性、可擴展和可維護的系統的思維方式轉變。 Nygard 提供了對軟體系統在生產中遇到的各種陷阱的見解,例如網路問題、不可預測的負載模式和硬體故障。他介紹了穩定性模式和反模式等概念,說明如何建立能夠優雅地處理故障並在壓力下保持穩健的系統。這本書充滿了現實生活中的故事和案例研究,展示了生產環境中不良系統設計所造成的災難性後果。 “放開它!”對於軟體專業人士來說,這是一個寶貴的資源,他們希望確保他們的系統不僅能正常執行,而且在面對現實世界的挑戰時具有彈性和可靠性。 **我從書中學到的最有價值的教訓:** 每個軟體工程師都應該在建立他們的軟體時考慮到生產。生產中的軟體負責營運您的業務、影響您的客戶並決定成功或失敗。 ### 站點可靠度工程 [*站點可靠性工程:Google 如何執行生產系統*](https://www.oreilly.com/library/view/site-reliability-engineering/9781491929117/) 作者:Betsy Beyer、Chris Jones、Jennifer Petoff 和 Niall理查德·墨菲(Richard Murphy) 對Google 用於管理其大規模、高度可靠系統的實踐和原則進行了富有洞察力的探索。本書介紹了站點可靠性工程 (SRE) 的概念,這是一門將軟體工程與 IT 營運相結合的學科,重點是建立可擴展且可靠的軟體系統。 作者都是 Google 的 SRE 領域經驗豐富的從業者,他們分享瞭如何建置、部署、監控和維護強大且有彈性的系統的專業知識。他們深入研究了 Google 使用的具體策略和技術,例如設定服務等級目標 (SLO)、有效管理變更以及平衡發布速度與服務可靠性的需求。這本書涵蓋了一系列主題,從 SRE 團隊的組織方面到事件管理和事後分析文化等技術實踐。這本書提供了對世界上最熟練的工程組織之一的內部運作的罕見了解,對於參與大型系統的操作、維護和擴展的任何人來說都是寶貴的資源。 **我從書中學到的最有價值的教訓:** 不存在完美的系統。透過明確定義和衡量 SLO 和錯誤預算,您可以就可靠性和速度之間的權衡做出明智的決策。 ### 改變你的問題,改變你的生活 [*改變你的問題,改變你的生活:領導力、指導和生活的 12 種強大工具*](https://www.goodreads.com/en/book/show/6665149),作者 Marilee Adams 探討了我們提出的問題可能會對我們的生活和職業生涯產生影響。亞當斯引入了「問題思維」的概念,這是一種透過深思熟慮和用心提問來轉變思維、行動和結果的方法。這本書強調了我們問自己的問題類型,從限制性的、判斷性的「判斷者」問題到更開放的、建設性的「學習者」問題,如何能顯著影響我們的觀點和結果。 亞當斯透過引人入勝的敘述闡述了她的想法,講述了一個人與生活挑戰作鬥爭並學習應用問題思維原則的故事。這種方法為個人提供了實用的工具和技術,以提高他們的溝通、決策和解決問題的能力。透過培養學習者心態並提出更好、更有說服力的問題,讀者可以被引導建立更積極、更有生產力的個人和專業關係。這本書對於領導者、教練以及任何希望增強與他人聯繫並更有效地駕馭複雜情況的能力的人來說特別有價值。 **我從書中學到的最有價值的教訓:**我意識到我經常處於「評判者」心態中。更加留意這一點,並有意識地選擇轉變為「學習者」心態,對我來說幾乎就像一種超能力,可以解決我面臨的任何挑戰。 ### 思考,快與慢 Daniel Kahneman 的 [*思考,快與慢*](https://www.amazon.de/-/en/Designing-Data-Intective-Applications-Reliable-Maintainable/dp/1449373321) 是對心理學與經濟學,深入研究我們如何思考和做出決策。卡尼曼介紹了兩種主導我們心理過程的不同思維模式:「系統1」(快速、直覺和情緒)和「系統2」(較慢、更深思熟慮和更邏輯)。卡尼曼在整本書中探討了這兩個系統對我們的判斷、決策以及我們感知周圍世界的方式的影響。 這本書全面探討了影響我們日常思維的各種認知偏見和啟發法。卡尼曼展示了我們的直覺系統 1(通常對我們很有幫助)也可能導致嚴重的錯誤和偏見。他也探討了系統 2 的功能和局限性,強調系統 1 的快速判斷如何影響和推翻它。這本書綜合了數十年的研究,提供了對人類思想和行為的複雜性的深入見解。對於任何有興趣了解我們在個人和職業環境中的選擇和行為背後的心理過程的人來說,這是一本必讀的書。 **我從書中學到的最有價值的教訓:**我了解到這兩種模式都很有價值,但也有其缺點。我學會了更了解影響我思考的偏見和啟發法,並有意識地選擇何時依賴系統 1,何時使用系統 2。 ### 原子習慣 James Clear 的[*原子習慣:一種簡單且行之有效的建立好習慣和改掉壞習慣的方法*](https://jamesclear.com/atomic-habits) 是一本變革性的指南,深入研究了習慣的科學以及習慣的小習慣改變可以帶來顯著的結果。作者提出了一個理解習慣如何形成的全面框架,並提供了培養好習慣和改掉壞習慣的實用策略。這本書的核心理念是,隨著時間的推移,微小的改進或「原子習慣」可以累積成重大的、改變生活的結果。 克利爾強調系統比目標更重要,他認為專注於實現目標的流程和系統比專注於目標本身更有效。他介紹了行為改變四定律──一套簡單、可操作的原則來引導習慣的形成。其中包括使線索明顯、渴望有吸引力、反應簡單以及獎勵令人滿意。透過結合科學研究、個人故事和現實世界的例子,克利爾闡述如何將這些原則應用於生活的各個方面,從健身和財務管理到生產力和個人成長。 《原子習慣》為培養持久的習慣提供了一個易於理解且引人注目的藍圖,對於任何想要在生活中做出積極、持久改變的人來說都是有價值的。 **我從這本書中學到的最有價值的教訓:** 透過對我的日常生活進行許多小改變,這些改變單獨地只會對我的生產力產生很小的影響,所有這些習慣結合起來會產生巨大的影響。 ### 有意識的商業 Fred Kofman 的 [*Conscious Business: How to Build Value Through Values*](https://www.amazon.de/-/en/Fred-Kofman/dp/1622032020) 是一本發人深省的書,探討了個人誠信和職業成功。作者提出了這樣的觀點:建立成功且可持續發展的企業的關鍵在於有意識的管理實踐,其中個人價值觀和道德原則處於決策過程的最前沿。該書認為,商業上的成功不僅在於經濟收益,還在於實現個人和職業成就。 科夫曼討論了有意識的商業的各個方面,包括問責制、責任、情緒智商、溝通技巧以及建設性解決衝突的能力。他強調領導者能夠激發信任、培養開放和誠實的文化並以同理心領導的重要性。透過現實世界的例子、實用的建議和練習,科夫曼指導讀者如何發展這些技能並將其應用到他們的職業生活中。 **我從書中學到的最有價值的教訓:**無條件回應能力的概念。我現在不斷提醒自己,無論情況如何,我都有權力和責任選擇對任何情況的反應。 「響應能力」是「響應」和「能力」的雙關語,強調自覺、主動回應的能力。 ### 首先,打破所有規則 [*首先,打破所有規則:世界上最偉大的管理者的不同做法*](https://store.gallup.com/p/en-us/10286/first-break-all-the-rules) 作者:Marcus Buckingham柯特·科夫曼(Curt Coffman)根據蓋洛普組織的研究提出了一種激進的管理方法。本書挑戰了有關領導力和管理的傳統智慧,提出最有效的管理者往往會違反標準做法。 本書的核心訊息是,偉大的管理者不會遵循單一模式或嚴格遵守傳統的管理原則。相反,他們透過專注於員工的個人優勢而不是試圖糾正他們的弱點來打破規則。作者認為,這種方法可以提高敬業度、生產力和整體工作滿意度。 白金漢和科夫曼確定了使世界上最好的管理者脫穎而出的關鍵見解和策略。其中包括選擇人才而不是簡單地填補職位的重要性,定義正確的結果而不是規定正確的步驟,關注優勢而不是沉迷於劣勢,以及為員工找到合適的人選而不是簡單地將他們晉升到下一個梯級。梯子。 **我從書中學到的最有價值的教訓:** 專注於優勢而不是劣勢的重要性。我學會了接受自己的弱點,並使用工具和策略來彌補它們,而不是試圖「修復」它們。相反,我投入時間和精力來發展自己的優勢,並嘗試為我所領導的人做同樣的事情。 ## 榮譽獎 在我從高級軟體工程師到技術主管的旅程中,我發現還有很多有價值的書籍。它們更專注於特定技術,這就是為什麼我沒有將它們包含在主列表中。儘管如此,我想在這裡提及它們,因為它們可能與您相關,具體取決於您所從事的領域/行業。 - [*資料庫內部架構*](https://www.databass.dev/),作者:Alex Petrov。我讀過的「最好的」資料庫書籍。它以一種非常容易理解的方式涵蓋了資料庫的所有基礎知識。對於任何使用資料庫的人來說,這是一本必讀的書。 - [*設計資料密集型應用程式*](https://www.amazon.de/-/en/Designing-Data-Intential-Applications-Reliable-Maintainable/dp/1449373321) 作者:Martin Kleppmann。建立資料密集型應用程式的綜合指南。它涵蓋了廣泛的主題,從資料庫和資料處理到分散式系統和串流處理。 - [*Oracle JRockit:權威指南*](https://www.packtpub.com/product/oracle-jrockit-the-definitive-guide/9781847198068),作者:Marcus Hirt 和 Marcus Lagergren。對於任何對 JVM 內部結構感興趣的人來說,這是一個很好的資源。 - [*Linux 程式介面*](https://man7.org/tlpi/) 作者:Michael Kerrisk。這是一本關於 Linux 的非常詳細的書,涵蓋了廣泛的主題,從基本的系統呼叫到進程組、訊號和套接字等高級主題。 ## 最後的想法 雖然書籍是個很好的學習工具,但它們並不能取代第一手經驗。你仍然需要犯自己的錯誤並從中學習。與他人討論你讀過的書,了解他們的觀點並挑戰你自己的觀點也很有幫助。也許您可以加入讀書俱樂部,或與同事或朋友一起閱讀。 我希望這份清單對您的職業生涯有所幫助。如果有一本書啟發了您並且您認為應該在此列表中,請在下面的評論中告訴我。 --- 原文出處:https://dev.to/frosnerd/books-that-helped-me-become-a-tech-lead-3831

每個開發者都應該收藏的 19 個 GitHub 儲存庫 📚👍

在當今動態的軟體開發世界中,保持最新的工具、程式庫和框架對於開發人員來說至關重要。 GitHub 提供了寶貴的儲存庫寶庫,可顯著提高您的開發技能和專業知識。 我整理了每個開發人員都應該了解的 19 個 GitHub 儲存庫的列表,為學習、實踐和靈感提供了豐富的資源。 每個儲存庫都分為子類別,以便於導航。我還加入了直接連結和描述,以便立即獲得印象。 --- ## 1\. [集算器SPL](https://github.com/SPLWare/esProc)(贊助) 集算器SPL是新一代資料處理語言,整合SQL資料庫,支援進階分析與平行處理。 透過集算器SPL,您可以輕鬆轉換和分析大量資料集,發現隱藏的模式和趨勢,並從資料中獲得可操作的見解。一些主要功能包括: **⚡ 頂級效能:** 透過集算器SPL的最佳化演算法和高效率的記憶體管理體驗快速的處理速度。 **🚀 豐富的函數庫:** 存取全面的預先建構函數集合,滿足各種資料操作任務。 **✨ 直覺的語法:** 享受清晰簡潔的語法,提升程式碼的可讀性和可維護性。 **👨‍💻 Java整合:** 透過JDBC將集算器SPL腳本無縫整合到Java程式中,縮小資料分析和應用開發之間的差距。 **🧙‍♀️獨立執行:**獨立執行集算器SPL腳本,超越傳統限制,擴展您的資料處理能力。 ![esProc SPL](https://cdn.hashnode.com/res/hashnode/image/upload/v1679824673641/82f843e0-72a1-44a4-bd99-68616f322534.png?w=1600p=84cro格式&格式=webp&自動=壓縮,格式&格式=webp) ⭐ 支援他們的 GitHub 倉庫:[https://github.com/SPLWare/esProc](https://github.com/SPLWare/esProc) --- ## 🌱 學習編碼 ### 2\. [awesome-roadmaps](https://github.com/liuchong/awesome-roadmaps) >***⭐*** *GitHub 星數 3k+* 各種程式語言、框架和工具的路線圖集合。 ### 3\. [awesome-courses](https://github.com/prakhar1989/awesome-courses) >***⭐*** *GitHub 星數超過 50k* 用於學習程式設計、網路開發和其他技術技能的精選線上課程清單。 ### 4\. [free-certifications](https://github.com/cloudcommunity/Free-Certifications) >***⭐*** *GitHub 星數 12k+* 各種技術主題的認證和培訓課程的綜合清單。 ### 5\. [awesome-algorithms](https://github.com/tayllan/awesome-algorithms) >***⭐*** *GitHub 星數超過 15k* 用於學習和練習演算法和資料結構的資源集合。 ### 6\. [awesome-interview-questions](https://github.com/DopplerHQ/awesome-interview-questions) >***⭐*** *GitHub 星數 59k+* 軟體開發角色的常見面試問題彙編。 --- ## 🧑‍💻 建設專案 ### 7\. [awesome-for-beginners](https://github.com/MunGell/awesome-for-beginners) >***⭐*** *GitHub 星數 58k+* 適合初學者的專案想法和資源清單。 ### 8\. [應用程式想法](https://github.com/florinpop17/app-ideas) >***⭐*** *GitHub 星數 69k+* 適用於各種程式設計平台和技能水平的大量應用程式創意。 ### 9\. [邊玩邊學](https://github.com/lmammino/awesome-learn-by-playing) >***⭐*** *GitHub 星數 115+* 一系列遊戲和互動專案,可提高編碼技能。 ### 10\. [專案為基礎的學習](https://github.com/practical-tutorials/project-based-learning) >***⭐*** *GitHub 星數 123k+* 針對各個技術領域的基於專案的學習資源清單。 ### 11\. [build-your-own-x](https://github.com/codecrafters-io/build-your-own-x) >***⭐*** *GitHub 星數 229k+* 關於如何建立您自己的程式語言、工具和框架的指南集合。 --- ## 🚀 工具和資源 ### 12\. [免費開發](https://github.com/ripienaar/free-for-dev) >***⭐*** *GitHub 星數 76k+* 為開發人員提供的免費工具和資源的精選清單。 ### 13\. [awesome-selfhosted](https://github.com/awesome-selfhosted/awesome-selfhosted) >***⭐*** *GitHub 星數 157k+* 用於各種目的的自託管軟體應用程式的集合。 ### 14\. [棒設計工具](https://github.com/goabstract/Awesome-Design-Tools) >***⭐*** *GitHub 星數超過 30k* 用於各種設計目的的設計工具的綜合清單。 ### 15\. [awesome-stock-resources](https://github.com/neutraltone/awesome-stock-resources) >***⭐*** *GitHub 星數 11k+* 免費和付費庫存照片、圖標和其他設計資源的集合。 --- ## 💯 模式與最佳實踐 ### 16\. [awesome-sre](https://github.com/dastergon/awesome-sre) >***⭐*** *GitHub 星數超過 10k* 用於學習和實施站點可靠性工程實踐的資源集合。 ### 17\. [棒設計模式](https://github.com/DovAmir/awesome-design-patterns) >***⭐*** *GitHub 星數 33k+* 軟體設計模式及其應用的目錄。 ### 18\. [美麗文件](https://github.com/matheusfelipeog/beautiful-docs) >***⭐*** *GitHub 星數 8k+* 用於建立美觀且有效的文件的資源和最佳實踐的集合。 ### 19\. [很棒的可擴展性](https://github.com/binhnguyennus/awesome-scalability) >***⭐*** *GitHub 星數 49k+* 有關軟體系統可擴展性、效能和優化的精選資源清單。 --- 寫作一直是我的熱情,幫助和激勵人們讓我感到很高興。如果您有任何疑問,請隨時與我們聯繫! 透過訂閱[我的電子報](https://madzadev.substack.com/),確保獲得我發現的最好的資源、工具、生產力技巧和職業發展技巧! --- 原文出處:https://dev.to/madza/19-github-repositories-every-developer-should-bookmark-13bd

大資料模型 📊 與電腦記憶體 💾

資料管道是任何資料密集型專案的支柱。 **隨著資料集的成長**超出記憶體大小(「核心外」),**有效處理它們變得具有挑戰性**。 Dask 可以輕鬆管理大型資料集(核心外),提供與 Numpy 和 Pandas 的良好相容性。 ![管道](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m6nswebbzlo96ml1ofeb.png) --- 本文重點介紹 **Dask(用於處理核心外資料)與 Taipy** 的無縫集成,Taipy** 是一個用於 **管道編排和場景管理** 的 Python 庫。 --- ## Taipy - 您的 Web 應用程式建構器 關於我們的一些資訊。 **Taipy** 是一個開源程式庫,旨在輕鬆開發前端 (GUI) 和 ML/資料管道。 不需要其他知識(沒有 CSS,什麼都不需要!)。 它旨在加快應用程式開發,從最初的原型到生產就緒的應用程式。 ![QueenB 星星](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bvt5qn1yadra3epnb07v.gif) https://github.com/Avaiga/taipy 我們已經快有 1000 顆星了,沒有你就無法做到這一點🙏 --- ## 1. 範例應用程式 透過範例最好地演示了 Dask 和 Taipy 的整合。在本文中,我們將考慮包含 4 個任務的資料工作流程: - **資料預處理與客戶評分** 使用 Dask 讀取和處理大型資料集。 - **特徵工程和分割** 根據購買行為對客戶進行評分。 - **細分分析** 根據這些分數和其他因素將客戶分為不同的類別。 - **高價值客戶的總統計** 分析每個客戶群以獲得見解 我們將更詳細地探討這 4 個任務的程式碼。 請注意,此程式碼是您的 Python 程式碼,並未使用 Taipy。 在後面的部分中,我們將展示如何使用 Taipy 對現有資料應用程式進行建模,並輕鬆獲得其工作流程編排的好處。 --- 該應用程式將包含以下 5 個檔案: ``` algos/ ├─ algo.py # Our existing code with 4 tasks data/ ├─ SMALL_amazon_customers_data.csv # A sample dataset app.ipynb # Jupyter Notebook for running our sample data application config.py # Taipy configuration which models our data workflow config.toml # (Optional) Taipy configuration in TOML made using Taipy Studio ``` --- ## 2. Taipy 簡介 - 綜合解決方案 [Taipy](https://docs.taipy.io/) **不只是另一個編排工具**。 Taipy 專為 ML 工程師、資料科學家和 Python 開發人員設計,帶來了幾個基本且簡單的功能。 以下是**一些關鍵要素**,使 Taipy 成為令人信服的選擇: 1. **管道執行註冊表** 此功能使開發人員和最終用戶能夠: - 將每個管道執行註冊為「*場景*」(任務和資料節點圖); - 精確追蹤每個管道執行的沿襲;和 - 輕鬆比較場景、監控 KPI 並為故障排除和微調參數提供寶貴的見解。 2. **管道版本控制** Taipy 強大的場景管理使您能夠輕鬆調整管道以適應不斷變化的專案需求。 3. **智能任務編排** Taipy 讓開發人員可以輕鬆地對任務和資料來源網路進行建模。 此功能透過以下方式提供對任務執行的內建控制: - 並行執行您的任務;和 - 任務“跳過”,即選擇要執行的任務並 要繞過哪個。 4. **任務編排的模組化方法** 模組化不僅僅是 Taipy 的一個流行詞;這是一個核心原則。 設定可以互換使用的任務和資料來源,從而產生更乾淨、更易於維護的程式碼庫。 --- ## 3. Dask 簡介 Dask 是一個流行的分散式運算 Python 套件。 Dask API 實作了熟悉的 Pandas、Numpy 和 Scikit-learn API - ,這使得許多已經熟悉這些 API 的資料科學家更愉快地學習和使用 Dask。 如果您是 Dask 新手,請查看 Dask 團隊撰寫的精彩 Dask [10 分鐘簡介](https://docs.dask.org/en/stable/10-minutes-to-dask.html)。 --- ## 4. 應用:顧客分析 (*algos/algo.py*) ![DAG 架構](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ru69b6jmhl73s9xxx2n.png) *我們的 4 項任務的圖表(在 Taipy 中可視化),我們將在下一節中對其進行建模。* 我們現有的程式碼(不含 Taipy)包含 4 個函數,您也可以在上圖中看到: - 任務 1:*預處理和評分* - 任務 2:*特徵化與細分* - 任務 3:*分段分析* - 任務 4:*high_value_cust_summary_statistics* 您可以瀏覽以下定義了 4 個函數的 *algos/algo.py* 腳本,然後繼續閱讀每個函數的簡要說明: ``` ### algos/algo.py import time import dask.dataframe as dd import pandas as pd def preprocess_and_score(path_to_original_data: str): print("__________________________________________________________") print("1. TASK 1: DATA PREPROCESSING AND CUSTOMER SCORING ...") start_time = time.perf_counter() # Start the timer # Step 1: Read data using Dask df = dd.read_csv(path_to_original_data) # Step 2: Simplify the customer scoring formula df["CUSTOMER_SCORE"] = ( 0.5 * df["TotalPurchaseAmount"] / 1000 + 0.3 * df["NumberOfPurchases"] / 10 + 0.2 * df["AverageReviewScore"] ) # Save all customers to a new CSV file scored_df = df[["CUSTOMER_SCORE", "TotalPurchaseAmount", "NumberOfPurchases", "TotalPurchaseTime"]] pd_df = scored_df.compute() end_time = time.perf_counter() # Stop the timer execution_time = (end_time - start_time) * 1000 # Calculate the time in milliseconds print(f"Time of Execution: {execution_time:.4f} ms") return pd_df def featurization_and_segmentation(scored_df, payment_threshold, score_threshold): print("__________________________________________________________") print("2. TASK 2: FEATURE ENGINEERING AND SEGMENTATION ...") # payment_threshold, score_threshold = float(payment_threshold), float(score_threshold) start_time = time.perf_counter() # Start the timer df = scored_df # Feature: Indicator if customer's total purchase is above the payment threshold df["HighSpender"] = (df["TotalPurchaseAmount"] > payment_threshold).astype(int) # Feature: Average time between purchases df["AverageTimeBetweenPurchases"] = df["TotalPurchaseTime"] / df["NumberOfPurchases"] # Additional computationally intensive features df["Interaction1"] = df["TotalPurchaseAmount"] * df["NumberOfPurchases"] df["Interaction2"] = df["TotalPurchaseTime"] * df["CUSTOMER_SCORE"] df["PolynomialFeature"] = df["TotalPurchaseAmount"] ** 2 # Segment customers based on the score_threshold df["ValueSegment"] = ["High Value" if score > score_threshold else "Low Value" for score in df["CUSTOMER_SCORE"]] end_time = time.perf_counter() # Stop the timer execution_time = (end_time - start_time) * 1000 # Calculate the time in milliseconds print(f"Time of Execution: {execution_time:.4f} ms") return df def segment_analysis(df: pd.DataFrame, metric): print("__________________________________________________________") print("3. TASK 3: SEGMENT ANALYSIS ...") start_time = time.perf_counter() # Start the timer # Detailed analysis for each segment: mean/median of various metrics segment_analysis = ( df.groupby("ValueSegment") .agg( { "CUSTOMER_SCORE": metric, "TotalPurchaseAmount": metric, "NumberOfPurchases": metric, "TotalPurchaseTime": metric, "HighSpender": "sum", # Total number of high spenders in each segment "AverageTimeBetweenPurchases": metric, } ) .reset_index() ) end_time = time.perf_counter() # Stop the timer execution_time = (end_time - start_time) * 1000 # Calculate the time in milliseconds print(f"Time of Execution: {execution_time:.4f} ms") return segment_analysis def high_value_cust_summary_statistics(df: pd.DataFrame, segment_analysis: pd.DataFrame, summary_statistic_type: str): print("__________________________________________________________") print("4. TASK 4: ADDITIONAL ANALYSIS BASED ON SEGMENT ANALYSIS ...") start_time = time.perf_counter() # Start the timer # Filter out the High Value customers high_value_customers = df[df["ValueSegment"] == "High Value"] # Use summary_statistic_type to calculate different types of summary statistics if summary_statistic_type == "mean": average_purchase_high_value = high_value_customers["TotalPurchaseAmount"].mean() elif summary_statistic_type == "median": average_purchase_high_value = high_value_customers["TotalPurchaseAmount"].median() elif summary_statistic_type == "max": average_purchase_high_value = high_value_customers["TotalPurchaseAmount"].max() elif summary_statistic_type == "min": average_purchase_high_value = high_value_customers["TotalPurchaseAmount"].min() median_score_high_value = high_value_customers["CUSTOMER_SCORE"].median() # Fetch the summary statistic for 'TotalPurchaseAmount' for High Value customers from segment_analysis segment_statistic_high_value = segment_analysis.loc[ segment_analysis["ValueSegment"] == "High Value", "TotalPurchaseAmount" ].values[0] # Create a DataFrame to hold the results result_df = pd.DataFrame( { "SummaryStatisticType": [summary_statistic_type], "AveragePurchaseHighValue": [average_purchase_high_value], "MedianScoreHighValue": [median_score_high_value], "SegmentAnalysisHighValue": [segment_statistic_high_value], } ) end_time = time.perf_counter() # Stop the timer execution_time = (end_time - start_time) * 1000 # Calculate the time in milliseconds print(f"Time of Execution: {execution_time:.4f} ms") return result_df ``` --- ### 任務 1 - 資料預處理與客戶評分 Python 函數:*preprocess_and_score* 這是管道中的第一步,也許也是最關鍵的一步。 它使用 **Dask** 讀取大型資料集,專為大於記憶體的計算而設計。 然後,它根據“*TotalPurchaseAmount*”、“*NumberOfPurchases*”和“*AverageReviewScore*”等各種指標,在名為 *scored_df* 的 DataFrame 中計算“*Customer Score*”。 使用 Dask 讀取和處理資料集後,此任務將輸出一個 Pandas DataFrame,以供其餘 3 個任務進一步使用。 --- ### 任務 2 - 特徵工程與分割 Python 函數:*featureization_and_segmentation* 此任務採用評分的 DataFrame 並新增功能,例如高支出指標。 它還根據客戶的分數對客戶進行細分。 --- ### 任務 3 - 細分分析 Python 函數:*segment_analysis* 此任務採用分段的 DataFrame 並根據客戶細分執行分組分析以計算各種指標。 --- ### 任務 4 - 高價值客戶的總統計 Python 函數:*high_value_cust_summary_statistics* 此任務對高價值客戶群進行深入分析並傳回匯總統計資料。 --- ## 5. 在 Taipy 中建模工作流程 (*config.py*) ![工作室中的 DAG](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5kyz7k3akkcbs48psodi.png) *Taipy DAG — Taipy「任務」為橘色,「資料節點」為藍色。* 在本節中,我們將建立對變數/參數進行建模的Taipy 配置(表示為[“資料節點”](https://docs.taipy.io/en/latest/manuals/core/concepts/data-node/ ))和 Taipy 中的函數(表示為 [“Tasks”](https://docs.taipy.io/en/latest/manuals/core/concepts/task/))。 --- 請注意,以下 *config.py* 腳本中的此配置類似於定義變數和函數 - 只不過我們定義的是「藍圖變數」(資料節點)和「藍圖函數」(任務)。 我們通知 Taipy 如何呼叫我們之前定義的函數、資料節點的預設值(我們可能會在執行時覆蓋)以及是否可以跳過任務: ``` ### config.py from taipy import Config from algos.algo import ( preprocess_and_score, featurization_and_segmentation, segment_analysis, high_value_cust_summary_statistics, ) # -------------------- Data Nodes -------------------- path_to_data_cfg = Config.configure_data_node(id="path_to_data", default_data="data/customers_data.csv") scored_df_cfg = Config.configure_data_node(id="scored_df") payment_threshold_cfg = Config.configure_data_node(id="payment_threshold", default_data=1000) score_threshold_cfg = Config.configure_data_node(id="score_threshold", default_data=1.5) segmented_customer_df_cfg = Config.configure_data_node(id="segmented_customer_df") metric_cfg = Config.configure_data_node(id="metric", default_data="mean") segment_result_cfg = Config.configure_data_node(id="segment_result") summary_statistic_type_cfg = Config.configure_data_node(id="summary_statistic_type", default_data="median") high_value_summary_df_cfg = Config.configure_data_node(id="high_value_summary_df") # -------------------- Tasks -------------------- preprocess_and_score_task_cfg = Config.configure_task( id="preprocess_and_score", function=preprocess_and_score, skippable=True, input=[path_to_data_cfg], output=[scored_df_cfg], ) featurization_and_segmentation_task_cfg = Config.configure_task( id="featurization_and_segmentation", function=featurization_and_segmentation, skippable=True, input=[scored_df_cfg, payment_threshold_cfg, score_threshold_cfg], output=[segmented_customer_df_cfg], ) segment_analysis_task_cfg = Config.configure_task( id="segment_analysis", function=segment_analysis, skippable=True, input=[segmented_customer_df_cfg, metric_cfg], output=[segment_result_cfg], ) high_value_cust_summary_statistics_task_cfg = Config.configure_task( id="high_value_cust_summary_statistics", function=high_value_cust_summary_statistics, skippable=True, input=[segment_result_cfg, segmented_customer_df_cfg, summary_statistic_type_cfg], output=[high_value_summary_df_cfg], ) scenario_cfg = Config.configure_scenario( id="scenario_1", task_configs=[ preprocess_and_score_task_cfg, featurization_and_segmentation_task_cfg, segment_analysis_task_cfg, high_value_cust_summary_statistics_task_cfg, ], ) ``` 號 您可以在[此處的文件](https://docs.taipy.io/en/latest/manuals/core/config/)中閱讀有關配置場景、任務和資料節點的更多資訊。 --- ### Taipy Studio [Taipy Studio](https://docs.taipy.io/en/latest/manuals/studio/config/) **是來自Taipy 的VS Code 擴充功能**,讓您**透過簡單的方式建置和視覺化您的管道拖放互動**。 Taipy Studio 提供了一個圖形編輯器,您可以在其中建立 Taipy 配置**存儲在 TOML 文件中**,您的 Taipy 應用程式可以加載並執行這些配置。 編輯器將場景表示為圖形,其中節點是資料節點和任務。 --- *作為本節中 config.py 腳本的替代方案,您可以使用 Taipy Studio 產生 config.toml 設定檔。 本文的倒數第二部分將提供有關如何使用 Taipy Studio 建立 config.toml 設定檔的指南。* --- ## 6. 場景建立與執行 執行 Taipy 場景涉及: - 載入配置; - 執行 Taipy Core 服務;和 - 建立並提交場景以供執行。 這是基本的程式碼模板: ``` import taipy as tp from config import scenario_cfg # Import the Scenario configuration tp.Core().run() # Start the Core service scenario_1 = tp.create_scenario(scenario_cfg) # Create a Scenario instance scenario_1.submit() # Submit the Scenario for execution # Total runtime: 74.49s ``` --- ### 跳過不必要的任務執行 Taipy 最實用的功能之一是,如果任務的輸出已經計算出來,它能夠跳過任務執行。 讓我們透過一些場景來探討這一點: --- #### 更改付款閾值 ``` # Changing Payment Threshold to 1600 scenario_1.payment_threshold.write(1600) scenario_1.submit() # Total runtime: 31.499s ``` *發生了什麼事*:Taipy 夠聰明,可以跳過任務 1,因為付款閾值只影響任務 2。 在這種情況下,透過使用 Taipy 執行管道,我們發現執行時間減少了 50% 以上。 --- #### 更改細分分析指標 ``` # Changing metric to median scenario_1.metric.write("median") scenario_1.submit() # Total runtime: 23.839s ``` *會發生什麼事*:在這種情況下,只有任務 3 和任務 4 受到影響。 Taipy 巧妙地跳過任務 1 和任務 2。 --- #### 更改總計統計類型 ``` # Changing summary_statistic_type to max scenario_1.summary_statistic_type.write("max") scenario_1.submit() # Total runtime: 5.084s ``` *發生了什麼事*:這裡,只有任務 4 受到影響,Taipy 僅執行此任務,跳過其餘任務。 Taipy 的智慧任務跳過功能不僅能節省時間,還能節省時間。它是一個資源優化器,在處理大型資料集時變得非常有用。 --- ## 7. Taipy Studio 您可以使用 Taipy Studio 建置 Taipy *config.toml* 設定檔來取代定義 *config.py* 腳本。 ![Studio 內的 DAG](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ct0bcisreqmg56mk4fgm.png) 首先,使用擴展市場安裝 [Taipy Studio ](https://marketplace.visualstudio.com/items?itemName=Taipy.taipy-studio)擴充。 --- ### 建立配置 - **建立設定檔**:在 VS Code 中,導覽至 Taipy Studio,然後透過點擊參數視窗上的 + 按鈕啟動新的 TOML 設定檔。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8jqe1fq87jaauf56b7hg.png) - 然後右鍵單擊它並選擇 **Taipy:顯示視圖**。 ![配置顯示視圖](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v7rkyipli0oq13iw8mxc.png) - **新增實體**到您的 Taipy 配置: 在 Taipy Studio 的右側,您應該會看到一個包含 3 個圖示的列表,可用於設定管道。 ![配置圖示](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tyxvv15nu9xr87n5y7q1.png) 1. 第一項是新增資料節點。您可以將任何 Python 物件連結到 Taipy 的資料節點。 2. 第二項用於新增任務。任務可以連結到預先定義的 Python 函數。 3. 第三項是新增場景。 Taipy 讓您在一個配置中擁有多個場景。 --- #### - 資料節點 **輸入資料節點**:建立一個名為“*path_to_data*”的資料節點,然後導航到“詳細資料”選項卡,新增屬性“*default_data*”,並將“*SMALL_amazon_customers_data.csv*”貼上為您的資料的路徑資料集。 --- **中間資料節點**:我們需要再增加四個資料節點:「*scored_df*」、「*segmented_customer_df*」、「*segment_result*」、「*high_value_summary_df*」。透過 Taipy 的智慧設計,您無需為這些中間資料節點進行任何配置;系統會巧妙地處理它們。 --- **具有預設值的中間資料節點**:我們最終定義了另外四個中間資料節點,並將「*default_data*」屬性設為以下內容: - payment_threshold: “1000:int” ![資料節點檢視](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/odkrz0pq2dhqpm0gnta2.png) - 分數閾值:“1.5:浮動” - 測量:“平均值” -summary_statistic_type:“中位數” --- #### - 任務 點擊新增任務按鈕,您可以配置新任務。 新增四個任務,然後**將每個任務連結到「詳細資料」標籤下的對應函數**。 Taipy Studio 將掃描您的專案資料夾並提供可供選擇的分類函數列表,並按 Python 檔案排序。 --- **任務 1** (*preprocess_and_score*):在 Taipy studio 中,您可以按一下「任務」圖示以新增任務。 您可以將輸入指定為“*path_to_data*”,將輸出指定為“*scored_df*”。 然後,在「詳細資料」標籤下,您可以將此任務連結到 *algos.algo.preprocess_and_score* 函數。 ![任務流程及評分](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wnc57wbxafjh2s3m6fat.png) --- **任務 2** (*featurization_and_segmentation*):與任務 1 類似,您需要指定輸入 (“*scored_df*”、“* payment_threshold*”、“*score_threshold*”) 和輸出 (“*segmented_customer_df*”) ” )。將此任務連結到 *algos.algo.featurization_and_segmentation* 函數。 ![任務特徵化](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mbtm200u9meq1x1rcy2w.png) --- **任務 3** (*segment_analysis*):輸入為“*segmented_customer_df*”和“*metric*”,輸出為“*segment_result*”。 連結到 *algos.algo.segment_analysis* 函數。 ![任務片段分析](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wnnl1w1q0blebzbyawvt.png) --- **任務 4** (high_value_cust_summary_statistics):輸入包含「*segment_result*」、「*segmented_customer_df*」和「*summary_statistic_type*」。輸出為“*high_value_summary_df*”。連結到 *algos.algo.high_value_cust_summary_statistics* 函數。 ![任務統計](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tynu6e718z1dwf8id05m.png) --- ## 結論 Taipy 提供了一種**智慧方式來建立和管理資料管道**。 特別是可跳過的功能使其成為優化運算資源和時間的強大工具,在涉及大型資料集的場景中特別有用。 Dask 提供了資料操作的原始能力,而 Taipy 增加了一層智能,使您的管道不僅強大而且智能。 --- 其他資源 如需完整程式碼和 TOML 配置,您可以存取此 [GitHub 儲存庫](https://github.com/Avaiga/demo-dask-customer-analysis/tree/develop)。若要深入了解 Taipy,請參閱[官方文件](https://docs.taipy.io/en/latest/)。 一旦您了解 Taipy 場景管理,您就可以更有效率地為最終用戶建立資料驅動的應用程式。只需專注於您的演算法,Taipy 就會處理剩下的事情。 --- ![很多](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ua3x4t3yttba6g25jjqo.gif) 希望您喜歡這篇文章! --- 原文出處:https://dev.to/taipy/big-data-models-vs-computer-memory-4po6

最漂亮的 50 個 VS Code 主題

原文出處:https://dev.to/softwaredotcom/50-vs-code-themes-for-2020-45cc 如果您正在尋找新的主題來在新的一年裡改變您的程式碼編輯器,我隨時為您提供協助!看看具有獨特調色板的各種時尚主題 - 從時尚到時髦到充滿活力以及介於兩者之間的一切 - 看看什麼最適合您。我甚至加入了一些有趣的圖標包來進一步自訂 VS Code。 我將這些 VS Code 主題分為以下部分: * [熱門](#trending) (1-20) * [深色](#dark) (21-30) * [光](#光) (31-40) * [多彩](#colorful) (41-50) * [獎勵:圖示](#icons) (51-56) 要在 VS Code 中安裝主題,只需存取市場並選擇您想要下載的主題。若要在已安裝的主題之間切換,請使用「CMD/CTRL + SHIFT + P」開啟命令調色板,然後輸入「首選項:顏色主題」。然後您可以在菜單中瀏覽您的主題。 ## 熱門 發現越來越流行的 VS Code 新趨勢主題。 ### 1. [激進](https://marketplace.visualstudio.com/items?itemName=dhedgecock.radical-vscode) ![](https://raw.githubusercontent.com/DHedgecock/radical-vscode/master/assets/editor.jpg) ### 2.[礦箱材質](https://marketplace.visualstudio.com/items?itemName=sainnhe.mine.box-material) ![](https://user-images.githubusercontent.com/37491630/69468770-671d3400-0d85-11ea-85a7-cf7ffedab468.png) ### 3. [Merko](https://marketplace.visualstudio.com/items?itemName=merko.merko-green-theme) ![](https://github.com/merko30/merko-green-theme/raw/master/img/s.png) ### 4. [東京之夜](https://marketplace.visualstudio.com/items?itemName=enkia.tokyo-night) ![](https://raw.githubusercontent.com/enkia/tokyo-night-vscode-theme/master/static/ss_tokyo_night.png) ### 5. [補救措施](https://marketplace.visualstudio.com/items?itemName=robertrossmann.remedy) ![](https://raw.githubusercontent.com/robertrossmann/vscode-remedy/master/resources/screenshots/gui.png) ### 6. [最小](https://marketplace.visualstudio.com/items?itemName=dawranliou.minimal-theme-vscode) ![](https://github.com/dawran6/minimal-theme-vscode/raw/master/screenshot.png) ### 7. [Aurora X](https://marketplace.visualstudio.com/items?itemName=marqu3s.aurora-x) ![](https://github.com/marqu3s10/Aurora-X/raw/master/images/screenshot.png) ### 8. [大西洋之夜](https://marketplace.visualstudio.com/items?itemName=mrpbennett.atlantic-night) ![](https://github.com/mrpbennett/atlantic-night-vscode-theme/raw/master/imgs/first-screen.png) ### 9. [玻璃使用者介面](https://marketplace.visualstudio.com/items?itemName=aregghazaryan.glass-ui) ![](https://user-images.githubusercontent.com/38076644/62824174-54eb0180-bbab-11e9-975e-2baf0e8cf33f.png) ### 10. [淡淡的丁香](https://marketplace.visualstudio.com/items?itemName=alexnho.a-touch-of-lilac-theme) ![](https://raw.githubusercontent.com/alexnho/vscode-a-touch-of-lilac-theme/master/images/workbench.png) ### 11. [FireFly Pro](https://marketplace.visualstudio.com/items?itemName=ankitcode.firefly) ![](https://raw.githubusercontent.com/ankitmlive/firefly-theme/master/assets/second-demo.png) ### 12. [ReUI](https://marketplace.visualstudio.com/items?itemName=barrsan.reui) ![](https://raw.githubusercontent.com/barrsan/react-italic-theme-vscode/master/sc.png) ### 13. [史萊姆](https://marketplace.visualstudio.com/items?itemName=smlombardi.slime) ![](https://github.com/smlombardi/theme-slime/raw/master/screenshots/screenshot.png) ### 14. [Signed Dark Pro](https://marketplace.visualstudio.com/items?itemName=enenumxela.signed-dark-pro) ![](https://raw.githubusercontent.com/alex-munene/vscode-signed-dark-pro/master/images/signed-dark-pro.png) ### 15. [黑暗](https://marketplace.visualstudio.com/items?itemName=wart.ariake-dark) ![](https://github.com/a-wart/ariake-dark/blob/master/misc/screenshot_frag.png?raw=true) ### 16. [時髦燈](https://marketplace.visualstudio.com/items?itemName=loilo.snazzy-light) ![](https://raw.githubusercontent.com/loilo/vscode-snazzy-light/master/screenshots/javascript.png) ### 17. [Spacegray](https://marketplace.visualstudio.com/items?itemName=ionutvmi.spacegray-vscode) ![](https://raw.githubusercontent.com/ionutvmi/spacegray-vscode/master/screenshots/eighties.png) ### 18. [Celestial](https://marketplace.visualstudio.com/items?itemName=apvarun.celestial) ![](https://github.com/apvarun/celestial-theme/raw/master/Preview.png) ### 19. [藍莓黑](https://marketplace.visualstudio.com/items?itemName=peymanslh.blueberry-dark-theme) ![](https://raw.githubusercontent.com/peymanslh/vscode-blueberry-dark-theme/master/screenshot.png) ### 20. [熊](https://marketplace.visualstudio.com/items?itemName=dahong.theme-bear) ![](https://raw.githubusercontent.com/shaodahong/theme-bear/master/bear-theme-snap.png) ## 深色 您喜歡在黑暗中工作嗎?發現 VS Code 的一些最佳深色主題。 您也可以透過安裝我們的[最佳深色主題包](https://marketplace.visualstudio.com/items?itemName=thegeoffstevens.best-dark-themes-pack)來安裝所有這些深色主題。 ### 21. [一暗專業版](https://marketplace.visualstudio.com/items?itemName=zhuangtongfa.Material-theme) ![](https://raw.githubusercontent.com/Binaryify/OneDark-Pro/master/static/screenshot2.png) ### 22. [德古拉官方](https://marketplace.visualstudio.com/items?itemName=dracula-theme.theme-dracula) ![](https://github.com/dracula/visual-studio-code/raw/master/screenshot.png) ### 23. [Nord](https://marketplace.visualstudio.com/items?itemName=arcticicestudio.nord-visual-studio-code) ![](https://raw.githubusercontent.com/arcticicestudio/nord-docs/develop/assets/images/ports/visual-studio-code/ui-overview-jsx.png) ### 24. [Palenight](https://marketplace.visualstudio.com/items?itemName=whizkydee.material-palenight-theme) ![](https://i.imgur.com/1mYWEP4.png) ### 25. [One Monokai](https://marketplace.visualstudio.com/items?itemName=azemoh.one-monokai) ![](https://github.com/azemoh/vscode-one-monokai/raw/master/screenshot-v0.2.0.png) ### 26. [夜貓子](https://marketplace.visualstudio.com/items?itemName=sdras.night-owl) ![](https://github.com/sdras/night-owl-vscode-theme/raw/master/first-screen.jpg) ### 27. [仙女座](https://marketplace.visualstudio.com/items?itemName=EliverLara.andromeda) ![](https://github.com/EliverLara/Andromeda/raw/master/images/andromeda.png) ### 28. [Darcula](https://marketplace.visualstudio.com/items?itemName=rokoroku.vscode-theme-darcula) ![](https://github.com/rokoroku/vscode-theme-darcula/raw/master/screenshot.png) ### 29. [地平線主題](https://marketplace.visualstudio.com/items?itemName=jolaleye.horizon-theme-vscode) ![](https://i.imgur.com/y0gi1ez.png) ### 30. [Cobalt2](https://marketplace.visualstudio.com/items?itemName=wesbos.theme-cobalt2) ![](https://raw.githubusercontent.com/wesbos/cobalt2-vscode/cobalt2-updates/images/ss.png) ## 光 想要程式碼編輯器更輕一些嗎?看看這些時尚的淺色主題。 您也可以透過安裝我們的[最佳淺色主題包](https://marketplace.visualstudio.com/items?itemName=thegeoffstevens.best-light-themes-pack)來安裝所有這些淺色主題。 ### 31. [原子一燈](https://marketplace.visualstudio.com/items?itemName=akamud.vscode-theme-onelight) ![](https://raw.githubusercontent.com/akamud/vscode-theme-onelight/master/screenshots/preview.png) ### 32. [Bluloco Light](https://marketplace.visualstudio.com/items?itemName=uloco.theme-bluloco-light) ![](https://raw.githubusercontent.com/uloco/theme-bluloco-light/master/screenshots/js.png) ### 33. [Brackets Light Pro](https://marketplace.visualstudio.com/items?itemName=fehey.brackets-light-pro) ![](https://raw.githubusercontent.com/EryouHao/brackets-light-pro/master/static/screenshot.png) ### 34. [作家](https://marketplace.visualstudio.com/items?itemName=xaver.theme-writer) ![](https://github.com/xaverh/theme-yscritwr/raw/master/screenshot.png) ### 35. [NetBeans Light](https://marketplace.visualstudio.com/items?itemName=obrejla.netbeans-light-theme) ![](https://github.com/obrejla/vscode-netbeans-light-theme/raw/master/images/vscode-netbeans-light-theme.png) ### 36. [安靜的燈光](https://marketplace.visualstudio.com/items?itemName=onecrayon.theme-quietlight-vsc) ![](https://github.com/onecrayon/theme-quietlight-vsc/raw/master/images/screenshot.png) ### 37. [跳燈](https://marketplace.visualstudio.com/items?itemName=bubersson.theme-hop-light) ![](https://raw.githubusercontent.com/bubersson/hop-theme-vscode/master/hop-light.png") ### 38. [NotepadPlusPlus Remixed](https://marketplace.visualstudio.com/items?itemName=sh4dow.theme-notepadplusplusremixed) ![](https://raw.githubusercontent.com/s-h-a-d-o-w/NotepadPlusPlus-Remixed-Theme/master/screenshot.png) ### 39. [GitHub Light](https://marketplace.visualstudio.com/items?itemName=Hyzeta.vscode-theme-github-light) ![](https://github.com/Hyzeta/vscode-theme-github-light/raw/master/screenshot/0.png) ### 40. [GitHub Plus](https://marketplace.visualstudio.com/items?itemName=thenikso.github-plus-theme) ![](https://github.com/thenikso/github-plus-theme/raw/master/screenshot.jpg) ## 多彩 厭倦了單色主題和沈悶的調色板?使用這些豐富多彩的主題為您的編輯器加入一些顏色。 您也可以透過安裝我們的[最佳彩色主題包](https://marketplace.visualstudio.com/items?itemName=thegeoffstevens.best-colorful-themes-pack)來安裝所有這些彩色主題。 ### 41. [紫色陰影](https://marketplace.visualstudio.com/items?itemName=ahmadawais.shades-of-purple) ![](https://raw.githubusercontent.com/ahmadawais/shades-of-purple-vscode/master/images/markdown.png) ### 42. [SynthWave](https://marketplace.visualstudio.com/items?itemName=RobbOwen.synthwave-vscode) ![](https://github.com/robb0wen/synthwave-vscode/raw/master/theme.jpg) ### 43. [藍色程式碼](https://marketplace.visualstudio.com/items?itemName=Sujan.code-blue) ![](https://i.imgur.com/JLCnwvi.jpg) ### 44. [賽博龐克](https://marketplace.visualstudio.com/items?itemName=max-SS.cyberpunk) ![](https://github.com/max-SS/cyberpunk/raw/master/assets/preview.png) ### 45. [LaserWave](https://marketplace.visualstudio.com/items?itemName=jaredkent.laserwave) ![](https://github.com/Jaredk3nt/laserwave/raw/master/screenshot.png) ### 46. [Zeonica](https://marketplace.visualstudio.com/items?itemName=andrewvallette.zeonica) ![](https://zeonicacom.files.wordpress.com/2018/09/zeonica_9502.png) ### 47. [潮人](https://marketplace.visualstudio.com/items?itemName=ModoNoob.vscode-hipster-theme) ![](https://github.com/ModoNoob/vscode-hipster-theme/raw/master/screenshot.png) ### 48. [野莓](https://marketplace.visualstudio.com/items?itemName=joebayer1340.wildberry-theme) ![](https://github.com/geoffstevens8/best-colorful-themes-pack/blob/master/images/wildberry.png?raw=true) ### 49. [Qiita](https://marketplace.visualstudio.com/items?itemName=Increments.qiita) ![](https://qiita-image-store.s3.amazonaws.com/0/6598/e054a4bb-cea1-8fc9-e193-fbb8376ed93d.png) ### 50. [軟體時代](https://marketplace.visualstudio.com/items?itemName=soft-aesthetic.soft-era-theme) ![](https://github.com/soft-aesthetic/soft-era-vs-code/raw/master/screenshot.png) ## 下一步是什麼? 想找更多主題?試試[搜尋 VS Code 市場](https://marketplace.visualstudio.com/search?target=VSCode&category=Themes&sortBy=Installs) 並依「主題」排序。開發人員已經建立了超過 2,500 個主題,您可以從中選擇來自訂 VS Code。 ___ 我喜歡建立讓開發人員滿意的工具。如果您喜歡這篇文章,您還應該查看我的其他專案: * [Code Time](https://www.software.com/code-time):自動程式設計指標和時間追蹤的免費擴展,就在您的編輯器中 * [SRC](https://www.software.com/src):在十分鐘或更短的時間內提供開發者世界的策略摘要 - 每週一次,直接發送到您的收件匣

JavaScript 系列九:發表作業&心得分享

第1課 ── 學習 Vue 元件基本觀念 [作業](https://tinyurl.com/yst8ytys) 第2課 ── 學習 Vue 的 props 觀念 [作業](https://play.vuejs.org/#eNrtF11vFFX0r1w3MW0JM7MYiWRZQCE+YBSJPLo+zO7c7oydvTPeuftRm000lQCWpESMoCFRowIJKU2MMVWqv6azLE/+Bc/9mrl3dtvSiPHFPmznnu9z7vm6a7U30tQd9HGtUWtmHRql7GyLRL00oQy9s3reD7r4MsWDCA/RMk16qFVzPRvOuVu101WuGfKCrkXwSFAGeNnvxwyttQhCnQTYCSYsa6C1iurjhdDxcU4b+MxfXJJ8CFHM+pToE0JpkjGQoY9cdJzQBtgyDCMGNggZ8o/hEbug0e3Y76xY6Nhv45ijLChN+iTAQQUuTeN/bW7qmyO/l8YYvHn/A4UZg/OarodZmATcV4lL+0xxlI6BeWGUuZY4N+1n4eIacl1XILmzaLwkJEtfSZbE2I2T7uIst6aTNsjfoc86YWmHHbwA47SBGO3jwrvQJ0GMqWkmBCrp+PEVllAfLjrD7CLDvcVWrSevjV4GqRAq9NaVdy+5GaMR6UbLq9JArnGpdECHUf+vBPMFWVagEb93U4V102iuxXZIS+r9nFA3DlnDcFBaV97fGakm9WmGFy2Du/uEcmkJnTtXSlCKZ61DZ7RJh2uohMFQYWGKJObp3PSKpgEHkJPGPsNwQqgZRAPUif0sOwOyk2C1VRPwCiYikPoXEsL8iGBa0ACVKL7iiND00cazT3cmt69N129Ovt5+9v3m9MbPJbopJCG2mmIQK2q+VSvUiPNFTgHAgdNLAhwDmAfP1bReqduzle9vy+Sra/nWnRdnS9GQDrZHyDc6nJIsqJRko8lJM7hoE1zRLHhNPFxlB4dJHGAKNODxdHcnv/qTSIb86gPwvKQ2TK2GanJ3O791f3LvRn7v9vTBFzNB0rarrqrjomMX4s5KOxnNRkrRmzbMhKndZywh6PVOHHVWOGPRZSHR8q27k+u3nm5/tvfnRtOTpDpDPUjRedmayoE0N1/DE2fVvGp68F3AK2O0UZyTVIgUBW1GEJh1sdmSTEuUlLJejZBrlXJ+AfElPHxbXq8chjzcPHR6lBnaD+Yu0vNoEgy9XYoxOYTPbMADZ1nwmT0IJcv2XDDTFqGGVmvSzOY3EJruWMRGGVoM2guLWNW3Rajcq5LOJK1VOmbWFd/6q+kZ7RWOGVuN+ecxOU96Pu1GpIHqoj+nfhDAyJLHcYu4vAFrwpEzjAIGM/9U/WVB3YuIE+KoG8LoP1XPBqGABlEG6lYbaDnGI1PMWaR0coTT9rMIBvOJuhDGieyWLkmrwhRzEFHcYVEChkMU+z0iUB/2MwbT1oFlhsFGCDj4xVTg/DjqEgf2uB4oNeBdH9aBExT3lBHVSv2PzKiU6YFWDCln5r/zRMGoVTdeO66rX2/uLzkOH0n5k9+fPtrQyzJHovzq+t6TX//avbm3c3/y5fZk85e9nY38+p3882+n63+0iMhdBJ/5j99NH27lj7+xpysvBAhAlcgee6K05uBhSuSPf2sRXeuThz/ku5stkm+uTz9Zb4SMpVnD8z7q+5lP3QAPPDAZtOmXgCdqx0OOo1Je7xrzHhAp76fFgqh2/itic1PbmLHsW3C15VuwYsc/n8A67ZNikXuOrUdZoFcf4/513TfEVQKyWFTb8PToCqUiBRNabKHKk8L48pmRUBjN7/lB1Ae/dYzPoYWT9XS0gBpoob6g91CpWPWWtTXpMhpDWh3eYKz1T8Y3hooqOkbdVUkKaQyV4mTRx5hDT2loke4REYxtWEBXBEa6AFmejhA8W6IAiTdYKWuodLxWr/Y191Ut3juGBpiyCJZaR5QlBCtJT6Nj3r51Yzxd/y8fu3zKp7c8j/9B1qswP1/Wm3rlSK2WgEVxWD1YxHOLA/7vVx4W89FrRa96s7Uyr1Je+Xfr5OTR62T8N2L3XWg=) 一開始方向錯誤,沒有懂老師出題的用意,就照先前的想法做了控制面板,後來才想清楚不是單純用vue做東西,而是做出quasar這種開發模板用的componen 第3課 ── 學習 Vue 的 events 觀念 [作業](https://play.vuejs.org/#eNrNV1tvG0UU/iuTVVHsNL7kIUJaArQplwgRhIjEC4vU8e7YXrI3ZmedGMtPIaJtIvJAaWkkbiK0qaqmCCGakhT+C/I6zlP+Amdmdta7rhPaChCWsto555uzc8755ptJR7sYBOVWRDRdmwtNagfsFcOz3cCnDC225yPGfA/Vqe8iQytXlIXPMLSXDM/wyKrAWqSOI4ehjuEhZPoQwCMeC3XUGYbpTnOnhRkuFCUQIUpYRD01QijE7QX7bTtkOvpA2dDQzX8BphD69RY8dMSadlgWk0Rw9XNwjTg6rHnRdw0t5zJ9x6fcRYk14mJklV1S7gYlxBsBhPYnREfV8mzOSv3Is3RUx05I8vCPI1grLJJGWYesw1NltmyH4Xw7HzXN7TU8mkCam2M3mqzm8C6dnmEQ0cAZRagUXxyX4kgiwwxHc3+GFHmdme01xuf4FjaXT0vSwnQZZrfPzNH2RufLDGeeKb9/qYOLtIwuehahoT9KtXwr28Rx/JWzEh3T7P8XW8+flmDNebLHudRWmjYbn9vYJj5XZv9EhqX/KsPn2IYfJm9dEG1ldwlr+hbXaOkTMlrwUm1GCDuEsoKhLdiwSHQeefBnaBMThlYUcYZfSAozdjbY89P//HrnZH/rySBKCsZGeTNxnr0S+VzBzGxCXnLEj6OIEShcYnChjDDmpxA38JrMVdLTDwaMuIGDGYERQnOW3UKmg8PwZWilb4HeCDt41NGm1toq1X0KKAcOMOTXh6eZoSnIBUmqEuGsSqDlDNGGSF0QS0HEIOMU5FJOMcg4OblKOURKtwyKM0z5+XvGJYimfGKAXhW0QwnJsmEE+dJAYnQKuiILWoGKwttcJVNnGIas7fDXKdl8F9OG7YGAiQYH2LKg+7AjKHHB0jW8Mm+GxK7YFoOGz1SrLwh0k3DVFIaw1RQmyw7hW21YkUNWhaWBAyGPMiASjtIK5Vb+FDYM8uuVYHe6sE9ChimT3wa+JKvVprXstYhfpCZKJTS4t9F7/MfR9d1476v+jUdH25/G62u9g18Hd28ffX43fvhjvP7w5HD7fSjS0huX0LuwtIYoNC9Fk7Eg1CuVsG7ymB+FZZ82KtzDqwih44Pfju5tpFcrDkIy/snhZm//dv/6g/7WL739jfjKzfjat4O1x3Kq4ASCYbzz3WD3fry3PVjb7N96cPz91uDqzxIzJE8O2L/xWXz/ZhYoKDkGE6/fifceJZoCvMpDNq8eX/ky3rkT/7SVXAEFvfq7P8SHiSXhUNZ0wXRsczkX6fjgm/4X1+LfN6G2vYODeOMWKpU4rdKdPO5uGlAfSqvkJZHoJUaHN5CMMufsic7nbFKk34ncGqGJKdHoed93CPYULhHorPVppKeWkRclQa4SnWRTydKA4xxxbVaYzIjJ5LRcdVFhdcFawKbyWoOjSRJPl9VIj4ykNmk5UkfNp3BleQ9bdgSVXMSsWca1sFBQOjFbhX1fLaISKqRqMCtMRVDtyWB1Mg3l2B5ZSPbqZRM7ZuFch9e0i6aSnVm8nILrvseWRMFz0CkhCRlcKhV/G1FmMg5YFUgU+o5tIXF+q1ldWUt5BHQ6yS7ogiZwZZMNO0Pcyqp9koLZ8nvwP5MQnWRZ6diM4IJI9cC34diiifipOHrTbxEKwQwWQhpEnynP8HUKiuWEqvsXUnaEYQ==) 嘗試從quasar的原始碼反向工程做出一樣的效果 第4課 ── 學習 Vue 的 v-model 觀念 [作業](https://play.vuejs.org/#eNrNVltv3EQU/iuDVdQN2mtuTc0m4iIh8YAEqtQXzIPXnt012B4zHm8SrRa1TSuVhrA8tAmKkKDqRakCSSsQDckGfgzr3eQpf4EzF3udTSraPvXB9pwz5z7nfOO29n4QFFsR1nStGlrUCdiC4TteQChDnyx/7AcRQ3VKPGRoxZJicHlDe9fw8ZKQs3HdjFyG2oaPkEVA2cc+C3XUTk108nzPNpmZm5ByCFHMIuonFEIOl7xquhHWkR+5rlBBqAOO4C0oD7MmsbllSS+azGqmFHcdMWynDI9EPtDcJWdwS9VSmiUQDHuBazIMFEJV22khyzXDcN7QasReNjTBhx2VRhKp7hEbuyJUEB3FbWiJxHtRAMni04I5Hy+K9QSaX0C5kR6aR+nWyIZr1rALanXHdbE94itaUKU3IkISMdfxszGmnEyU1RIUGFbVUqbsQIZs2eXLd2QreCZtOL6OyuLcA9O2Hb8hyY7hF/nBSMFFx2Zw+JVy+W0h2sROo8kEI2w1Bct2QnC0rKO6i5cEhy8KtkOxxRwCXiziRp4vtmqm9VWDQsvYBeASqiPaqOWm5vJo6hJ/JmQE0EEqYC2vZSaCT9BbhQI62l7tH/4zvLsV7/w4WP9ruHkzvrXSP/jz6Mnj4fdP4ueP4lvPT3qbV6GoVz76EH0K8UmvvBhNxoJQL5XCusVtfhkWCW2U+A6vI5iOD/aH26vJXHEZJM2f9L7r7z0e3N0ddP/o763GtzfiOz8frRxKzVZBnDMCRvzwl6Ot3+Kdzfha799r1+Puevz3BqyloDjSU2KDX2/2D9fiH9aGW89Oerfj7m7/4FF/b41nuNJFn0VmaFIUr94b3ts+vvFgsPXgqLt7vL8BAcVPnw2f3o/Xd47v7w4f7sc/bQ02rh/fuBOv/Q5mTnrfSp+yoRFoxr2uZCX9o5ioUFC9kgzvedATUALFSwBFZKKjK4xC/ygskZ509AEhLjZ9xU2cjfNHo8GhjC0H8FXmEscZuFIQJd/YczgAfm5oZ8bM0L54RSyyiM9MCJCOAElMZgqcdjLjowHUE+V2mrT85jPpplXujBR5mqDG8FLWWksBRDaNFEmEa9i8wLPOXTyT8cU8uoBbcCUUGcw2hq4dwxGKv45gJMcxTfZindBRegvttmrRTqdaEquXwpZiWkPVKiR0JABQDNJOCwsISLBnphxwuIBpN3zpbkzLrIUAHExqubguYEfoQAVJkKWo6ada0CWT5bIXIl52kwqBDNZU5qbyqHLpsngpuIHbWNygWcgDG8p6Co+TwHlppyOzep1YUYi+kUWFvpRcOCDHTrjStcgqsZ+JeW4mjyYrk/CameEhIxRapgszUS5eTlwV1YSrH4QX55sFYSkyC9A7O8sftU+ojUHdh3+MDKNQI4wRD+oAZYCjgejP01YNn6rzC0WNR5O0MIUCJLQsjIj4hS4Wm45qAVBiPKwa5XeQj8MwVymKesgCpJP2GiWYhhtoGpKYHitB5VSq5xg6L9t0+NN8U86ZjMddnD3q1MP/CZ5bn8rZG7XzH5rEyeY=) 同上 第5課 ── 學習 Vue 的 slots 觀念 [作業](https://play.vuejs.org/#eNqdVd1uG0UUfpWDEeJH3o0TCqkWUylBofiiroQbIaS9Ge+O7VHXM6uZsR0TWSoqkVADBFAFFarUIgpEKj8XVCjQwtNk3fQKHoEzM7trO2mo2ht7zpnv/M45325X1tLUHw5oJajUVSRZqs+FnPVTITVcGK8TzqmEjhR9CCv+UqExFmHljZDTLYuMaYcMEg3bIQeIBJpzyrUKYHvmZFI1lzHR5KWXHRBAUj2QHLYn6ApyRJ/qnoiNrZNHREe9UjLOB5rGpaIvBhxl49MojKf6UlkJCpr204RoihJAPWZDiBKi1JthpS3icVixerwpE5XoMaZxrgd4j0JE+IsaOozHMBYDCYoMaYzZRyylCjABlpgLUKzLgXHfBHbGZXgYeioROiCRZoKXzhHRHmiNmrcuNi81mpsbsNaCNTi/udG6VF/K7wpMq3G+CY1mqS+jLC1UaRRFObYJ/19go+OSJyPQPaagbWFVFGh+xkdANWW8C4pSDu2xsXimMt/faJ0oq3nxhOrfWzduPGWZRsTnxdMCDkWlx4k5vuLmrk9kl/EAanbqUhLHWJgTJyH3zVg44IjFGkdvuVZ7wUJ7lHV72irUsGdVMVMYaBxAV7LYarokRYSkfSuRBEfCiwTOKEdLpYnULk7IXXUuVFvImMoAOG6ONWyT6HLXvlSAE9Wjkhk7swCJQBz6jWg7GThwB/17in1AsQr/bBE7GkhlsKlgGF4eq9Z/rcClQjHzWgFONDaNDY1TzNDlFwSkg9bFbueFhBW7//PGpK1Egrtp1YwrijDX4lkt2Amb/qjHcqBIScQ0NtBBtSS8cJhfYaorChLGKTE1zLUu6IkhNm0+wZk7f8WBkQ3y569UK/MEZijvOc+DkB/d3c3u//nw7m7JVuYesp2rh/d//+fBJ4cHP0yv/zrdu3d4sJt9/HV27dbR1b9C/uj250f7Pz/85iMwIw+oy+7cnl7/O9v5Ptv5KfviWrbzY/bLHyF3yzCPym7uo6/DgyvTz76c3ryS7f2WfXjPmT769tPszleFab6rMN3/LnuwB55nxrukt8fRbypFapk3Nw1gXYiEEm759Wn40Tw2wbbLGUma66C4nwuRH6o5XwT4jtjACRrWTdXnMKT7cwta+ipcuQ4VcOCkTxe0x82ftOl+mXvelFNG3M/5LeeFLW+28mo4esxurZZbY/WjnBHO1Nz4min1SprwV0p0QjXOqKfMeLr1qy2vnn193leH9FmCk/uuaAstquCRNE2op8YKa6zC2pByhqy8jjEuXyBRy+rfRssqtGhXUNhs2C8iwDs0GVLNIoJWkpGkitzOlaeQRDqnLOTzq+3lDjErcwrFlMRhqC1nD3jVlWcamc/4sW4vcIIWyIy5CX77XZNKuWTSTkK3XFfw4I2k4VPze4JdLRP4xYbM0agnScwGuARnUuNpkQQm/wFjNTqv) 嘗試模仿quasar拼裝不同呃component 第6課 ── 學習用外部狀態管理 vue 元件 [作業](https://play.vuejs.org/#eNrtVktvFEcQ/ivFhshrsi+bWEo2hgBOohwgQiBx2gO9M727HWamx909axtrTwQFsBUOIRA45KEQHkJAFEUBYkj+jGdtn/gLqX7M7KyxwcohyiF7mO2u/rq6q+qrql4uHY3jWj+hpWZpVnqCxepwK2JhzIWCE0vHEqV4BB3BQ2iVavVMone0Sh8UkB8xEvBuEWklObIV0UWD9WmHJIGC5VYE4HFUENFIySYsw/wxFTXzYyswb3VokdM/qOhdPlGkPGk1AAiqEhHhdhJQoZrQIYGkFVQddZgI3RwGeAdw+0OqetzXR1oNZuPU9MGRTicro3DSbMy22u8CUV4Pt9uZNiJR1M8FIU8inGt1WqCPnq3n3sWJomEcEEVxBjA7X20rlOpDAtKmwaFW6ag+vVWyQo8HXKCwHRDvXCZUdFFVs5WFHlPoZrvSlOw8ReFUJhB4Hd8Oj8REoLertI9fxBgr4RDsMwO74fBs3dwou5xvXd+vhtw3l3NYs44In/XdEOA4FzQEFsskBF9fDiRTQNDhOh6SekoHC4jPYiaZx6Iu0ICpGpyiArcIGtMgoJGfyEyj3t/nQRIr9Fc2kqANYKgVKSV4th0dFPlMMSYhpqJD0VQfx4orEprA6B8lQBTwMMKVPg0gSsL5hIRAF6nwGJ7CkJAhkERVICIqkRAy5Dmp2LN0iNDImjO+PrK+GMdRJOeOc5mHZpdYvi6aO8RzLKJ7i6n+dQJO9Lpg3V4uHg82jm20dyXmnM2qf4GaLn+1IW64R3rm6P8J+t8k6G6R/Qckna0XSilOpVoK9PCALeQhEV2GLaVhanhMfB8DaqeDVtTm/pLFLTBfYT2fajTeNsge1ccbgez3jKiN7ugas6wbmvDWND3oHaRWF9Z3d3SpUio2v7HGulMLjAWPTfcz/D1DgoQ24RjnASWRaTdvah8YYPACIqV1rSIsoqJVwoxgHRSN1I5lRL5F9ojPF3BtjCpFxAKLECE1RAZcIdD9ZfhstFs0avm1nMkckwZZ3ATSlpgwSjsRgGH+odNtsDAvUNNSE7qC+TZ8yEiKzsfWGiHMwy8V1vujA5pt2kH2Z68Lh0Ui6TfI3k5+NdKi2y5PvT9dgemp9/Az494EPCaYj3jFRm3GCDoswCs1oW3YG1Epy7hkweer6EW6mJOv5rzqPJJRcwrL025863Q6Zikki1XH2JlGI160eC58KqoCK1eCdHrXifNjp7Ydexi250htxp79KptHjz7N5n3VKmw+WFl/8dfGtXvpo2+H159t3PoivXhhfe33zft3Nr66nz75Ob345OXzW2cSCqc/mYOTGElrjOZFTylkfL0uO57W+bmscdGt6xVNPVSdrv2x8WAlfwhqEFj9L5+vrj+9M7z2eHj1t/WnK+mlG+mV7zcvvCh0I8BpevuHzXsP00e3Ni+sDm8+3vrx6ublX7c3pzHg8PqX6cMbRaCpjztg0ot300fPLEYXvnHI6uWtS9+kt++mv1wtdDgY3vspfe4kEqs5MrQoOuIFzDs3pmlr7bvh11fSP1fRt+tra+nKTahWdY7tqZgU/NGE00ogt1x/0fbP7SA35m6TafOa8FkStqlwIlOft8GMiXnNyvYaK7dL+3MBdpuTMY+TeHxtL5WubejgbHPFKXQkyXqFdSUu7KchU+UJ23s+1q1nomKtnBw9RzTLEZu/+kdZhwVGeynvys6XufvyBZt4p1zenSCqV8PaUi7bwH+IKQqYXJNQhbKLPMqMaBLegYl4cSJXFWAF+9S1nrMeCbzy/mUdgwHmqk3PybM5uIPF7bQJ0Bj0gCkhBVxeWt6o0VqyE7BhkIAVk/n6EeOdK9zDMsL8OeHAvdTsbHnZ5dIAK4tuFjaMr+sXWVAtkYtBifDtU6h3BYGXCKkjFHPmGgOSXZAoK/gSraIw3WiE+Dgj0vXt/Khmj/ez/mSgWDJrrmgWyuHgb/u4VhA=) 稍微翻了quasar的原始碼,還是搞不懂為何上一個v-close-popup的attribute就可以讓按鈕有關掉modal的功能 很神奇 第7課 ── 學習開發狀態複雜的 vue 元件 [作業](https://play.vuejs.org/#eNrlWdty20YS/ZUJJSekQ4CgHMkWLXkTpdbaVG22UrJrX0SlNCSGJMoggABDijKL/57TcwGGAEQ5l7fYLgno6enL6Qt6xtvOD1nmr1eiM+pcFNM8yuS7cRItszSX7Lcf0zjN2SxPl2zc8Qc/PyoCsY87b8eJ2Ci2UMz4KpZsO04Ym6bYm4hEFiO2tRJ2fVoKueTdnmZjLBdylSf2jbGF2Iyg5SgYBsM3b8YdtYWxHfTgp3pbCrlIQxKs3x+4nC7KN9K8kiIsCct0leCdVBKBJF0MSh/xIsUyi7kUeGPsIozWbBrzorgcd6ZpInmUiHzcUYtYnqykTBP2/TSOpp/AAnvZJfvm6L368w0YpSjkxUDzKQVqH8QaEXj5zZsqQNbeMg1FrMWMO2xgtQwsu326GDhW4rWQjzE9vtTILXk+j5IRCxRMGQ/DKJnr19048Sdp+KgZH6JQAqthELxQrAsRzRdSEYr1wrCXbus9pbhhkG0aLO9YzYaKCzAbMzv9jpM1e0nWlj2HUySfT0bs9s5kBmNrHkfhzfXVHtHkUWsCZXmaqbxU6P+fxysxYh9kDicNh1hGlLm3484qgzFiVHGOO1pJlYVaARR+TG/mky4eStMpHZNC0uIN0gS//GI1KZSq7rDPXvWUWXuM1w3GV3122sJ41WA87bPXFaPB7TbjeSF+SiRZdtNnw7NeHzGtaNcttCtFuzOyNCgK+Y/pf8Smi4enfPzfajkROXHcBnc9X6Ya2C7E+cikD5LnsnvSR2yCcecJ9x0Zwz8jg5BxZJz8ARkGtPuj4y05tFO/rvWvq919DRBAj0yphXww+CRExmZRDmtiISWq5MguRjPW/Wrw61H3NvDOf/De322D/tmudzyIfGocSpQjizG5iApfdxm0RTSJb5tpZHn8WCRzuWAeG1YeoRAr1Xuan9d7TIXQba2CPpnR0GKBUTWJLShLEwjhSAcoxLESVZyEj4DMhfQVvZJLRhsWvcLeXbKAff213WioF5fs5PS06YGJkHou09e+9So9ht32Ehh26/u+ZbSFAAeZiAvRUAMed4sV4+yrVZIohASSUUj2OGY74VaPFeS11FvwJIxRrvjY/YjnuXCl6EqY8Fx/eGFZZe89bO0eb63ZqNJdnwX417svu6fhAtVhHCrGNq6g77Cd3O0cngoBbRN9OHI+/XR1yLafuVz4fFKUgYKRSGoK8GFbmxuH7sanbG9uOym3tfqiiyMXM3AT9ioM/izN/82ni25XxH0WJSF1hct3bq5oDJZRArdF7OPBSUCzyCn2tMjpM7q/iLzSiyrrnWWQ1LfWR1r9gs+byOUj6tbzkANq1qCCtflwq2y7c5N/MGAQfB/jk85zb57zMMLwhlDU9gDFJq1n2+KeJRNEeZ5j+Ao/RJ+p0rtUq4AVXvcwNGDk6LEB65LDhvgtWtwLNZyowdJUTmWnA/tDzjN42dD105LPSdk9AIumlSdqevXOg1DMy3geb+vZSMXAgheHOFAF7NWrgyyoAHZ2dpCF9JCfJXS6rBsTq15sazEItNNgnmxeLWyHuotGGEOZ/Ij5tgsT3ATW25uNx/qgHxpzuPlWKkvcLmW+tdYoPT7V7Cpl27YnNu8BpkLxKVmmYbxkgX9yfo6scrsBUU/fvHapKHaiDoffsXJGZ2z45qx6+RcycxIjghgpSyINmA+LSOpjUD2K9liiV9xRszrsKCj3/PiSYP+BgH9R0J8P/BcEv1aqNl4VIs8dvL7yPHZRrOf2DCRhC9vgbHSKAY092gd7NqNlnLa2W0oJttvRCWlDgunQRGKY5zVPdKZtQA66iPtutbrMEGyGneroFpHrlcdaChh/4YmI3eRwhCi43DX5mInShYpcOw46iYYeqUc7rL3eW1H9D1T0O1TESM2pZYHs3laN0VMUMFTh3729d2V9r3yDLGeq3VufxKscy7XZpWJpHl9rgCIxlY4C+K89fC5B60bltzKd0QnDRbvIeFLuxtp/+YRQbritqhDOOOWLxMDx7Ya+e+POtf51hcOb+WghY0otA1LzTIirz3xbkNtXTZjVokvHtw5kJLND4pTpGDja84G6lLb7UMD2jmctcWn6Zu1P1CzdcOCLDWiO+8dijc/uweT463cbjE3SjVdEnxVlkuahyD2QzCWFKe69m4+TQF9PwKCXZgeuLLINK1K4QPlHByr613vLXg5KHQsepg/Qir+n4AYfp5FTzaLGEqWd5o0VbgW+M1qqyxNs05S0iGSUwqNcwOloTW3YMXc0EagMc8SgwQE46qsMtT1KUH0lGqUsTK9pjO+tIn/2VKxKkKomoMuFqXpRa2nGp5F8BKt/ou2AJbZnaRvSlaS5cMQS3Ojt3RqdWizr10rU2TxMPEkBV5YjtiLHprzQ29UqMmYOu6fwTuSKPIOv3oMRfR5o28voa+D33RseBrRsN+Yeq43PiRDFVSutKQijAukJjGax0BYo4z1guESoSxdIZ9UJTABXeUGIZ2lUOlpN5SOmQMLNC2Q4aeSmZBUrgDP5FAE6oMmxb+rGxIbAXL9Z5LxYzNT93j41t9d+hlxG1LxXKQO0KNfRmvp0IDI/Av/MpH2VWxGN3iNWP0Osed6tPMY9U43QWj5NO6jMIf11oA8I9dVcABM4kKTm0SYzylyH4+MCnUmVtBOk0ciCWgBrGCAVlwrdQbjLi1NrqcW/tLzmUMPkUR0ItW7zRTzAD3K5anNOCzqhVG3d/2QxPOfzaJGuba8spjyGs0Nf539bA2zT3lCzTD8DABD+IbDW/P17IFUt7HZ/lrgjZcU/BVXj6N8DJ6Q7087+bHBm4HjiA0XqZzHpWERhKOjuZv9/OXa/A88llUk=) 研究了前輩的作業才發向若要讓input的值可以被檢查就不能限定number,要不然輸入非number會直接show出來,卡這個很久... 因為想學quasar的樣式(range條的顏色變化等)做了些研究,後來嘗試把所有想法塞進去,結果做出來是蠻炫的但不是很好看... 心得:覺得老師的出題方向就是幫助學生從業界的需求去學習,然後一點一點從小地方開始做,並且能夠自行研究,而且不強調怎麼寫,而是確實做出來,很務實的取向,覺得獲益良多,上完9堂課默默繳了不貴的學費,有新的課堂會再回來做。 目前正嘗試自行開發一個網頁應用,寫cdoe真的要很有耐心,其實想想現在有很多輔助/查詢工具真的很方便,越寫越佩服那些做框架的人...

[好文轉載]哇操!你敢信?花式寫todo-list,body裡面一行都沒有也能搞?

[【前端動手玩創意】哇操!你敢信?花式寫todo-list,body裡面一行都沒有也能搞?](https://ithelp.ithome.com.tw/articles/10312056) ## 前情提要 如果說蟑螂怕拖鞋,老鼠愛大米,任何事物都有相生相剋的道理,那麼前端最害怕什麼呢? 恐怕就是todo-list。 這應該是前端的四大惡夢之一,並不是因為太難了,而是因為太簡單而且太無聊了, 不只無聊,還是每次教學都必須寫的一個磨難,簡直是瞬間殺死靈魂中隊前端的愛。 今天要來用不同風格寫出todo-list,把代辦事項寫出新滋味。 body裡面一行都沒有也能搞? 就是可以搞,讓我們馬上來欣賞這段有特別滋味的玩法!ε(*´・∀・`)з゙ ## 程式碼 ``` <!DOCTYPE html> <html> <head> <title>Todo List</title> </head> <body></body> <script> //渲染DOM AddHtml(); //資料內容 function AddHtml() { const Data = { h1: "Todo List", button: "Add", }; //主體的DOM const html = `<h1>${Data.h1}</h1> <input type="text" id="input" /> <button onclick="CheckNull()">${Data.button}</button> <ul id="list"></ul>`; //渲染至畫面上 document.body.innerHTML += html; } //邏輯確認:是否有輸入值 function CheckNull() { if (!input.value.trim("")) { return; } else { AddItem(); } } //新增代辦事項 function AddItem() { const li = `<li>${document.getElementById("input").value}</li>`; document.getElementById("list").innerHTML += li; input.value = ""; } </script> </html> ``` [可以貼到try it的地方執行看看效果](https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_form_submit) ## 觀念筆記 所謂MVC架構就是模型、視圖、控制,背後其實有一個元素貫串任何程式,那就是:「邏輯」 每當你要下手寫一個程式卻不知道怎麼開始動手, 那就是邏輯沒有通順。 網頁不外乎就是畫面,以及資料,還有使用者的操作。 對於todo-list來說就是一個簡單的input畫面,使用者輸入的資料,點下按鈕送出的操作。 這段程式特地不寫任何一行body裡面的東西, 玩弄了一般人對於程式區分的概念。 用模板符的特性讓所有一切交給變數與函式處理,最後三個function: AddHtml、CheckNull、AddItem完美演繹了代辦清單這個網頁所需要構成的底層邏輯。 必須先加入畫面,然後確認使用者操作的條件,最後新增資料。 這樣子的流程對於新手或許不習慣,但是以邏輯面來看比一般人的寫法清晰許多。 這也是未來框架導入後,對資料流更敏感的培養練習。 ## 心得 無聊的todo-list竟然可以搞成這樣!? 真的是太有趣了(๑╹◡╹๑)! 原來前端的惡夢也可以變成寫不同風格的天堂,沒錯,寫程式就是這麼千變萬化! 重點是背後的邏輯抓到了,那麼想要怎麼寫,真的就是藝術的發揮。 請繼續關注, 跟著我們這個系列繼續動手玩創意!!未來還有更多更新鮮的花招呢(。◕∀◕。)

在 JavaScript 中使用 Regex 正規表示式:懶人 Cheat Sheet 備忘單

需要字串比對、搜尋等等功能時,regex 正規表示式非常好用。以下是一份 regex 的備忘單,方便需要時可以翻閱。 - 原文出處:https://dev.to/emmabostian/regex-cheat-sheet-2j2a --- **測試正規表示式** - 使用 `.test()` 方法 ``` let testString = "My test string"; let testRegex = /string/; testRegex.test(testString); ``` **測試多種模式** - 使用 OR 運算子 (|) ``` const regex = /yes|no|maybe/; ``` **忽略大小寫** - 使用 `i` 標誌不區分大小寫 ``` const caseInsensitiveRegex = /ignore case/i; const testString = 'We use the i flag to iGnOrE CasE'; caseInsensitiveRegex.test(testString); // true ``` **將第一個符合項提取到變數** - 使用 `.match()` 函數 ``` const match = "Hello World!".match(/hello/i); // "Hello" ``` **提取所有符合項到陣列中** - 使用`g`標誌 ``` const testString = "Repeat repeat rePeAT"; const regexWithAllMatches = /Repeat/gi; testString.match(regexWithAllMatches); // ["Repeat", "repeat", "rePeAT"] ``` **匹配任意字元** - 使用通配字元`.`作為任何字元的佔位符 ``` // To match "cat", "BAT", "fAT", "mat" const regexWithWildcard = /.at/gi; const testString = "cat BAT cupcake fAT mat dog"; const allMatchingWords = testString.match(regexWithWildcard); // ["cat", "BAT", "fAT", "mat"] ``` **用多種可能性匹配單個字元** - 定義一組您希望匹配的字元 - 放在中括號內即可`[]` ``` // Match "cat" "fat" and "mat" but not "bat" const regexWithCharClass = /[cfm]at/g; const testString = "cat fat bat mat"; const allMatchingWords = testString.match(regexWithCharClass); // ["cat", "fat", "mat"] ``` **匹配字母表中的字母** - 使用字元集合 `[a-z]` ``` const regexWithCharRange = /[a-e]at/; const catString = "cat"; const batString = "bat"; const fatString = "fat"; regexWithCharRange.test(catString); // true regexWithCharRange.test(batString); // true regexWithCharRange.test(fatString); // false ``` **匹配特定的數字和字母** - 還可以使用連字符來匹配數字 ``` const regexWithLetterAndNumberRange = /[a-z0-9]/ig; const testString = "Emma19382"; testString.match(regexWithLetterAndNumberRange) // true ``` **匹配一個未知字元** - 要匹配您*不*想要的一組字元,請使用否定字元集 - 使用插入符號 `^` 即可 ``` const allCharsNotVowels = /[^aeiou]/gi; const allCharsNotVowelsOrNumbers = /[^aeiou0-9]/gi; ``` **匹配連續出現一次或多次的字元** - 使用`+`符號 ``` const oneOrMoreAsRegex = /a+/gi; const oneOrMoreSsRegex = /s+/gi; const cityInFlorida = "Tallahassee"; cityInFlorida.match(oneOrMoreAsRegex); // ['a', 'a', 'a']; cityInFlorida.match(oneOrMoreSsRegex); // ['ss']; ``` **匹配連續出現零次或多次的字元** - 使用星號`*` ``` const zeroOrMoreOsRegex = /hi*/gi; const normalHi = "hi"; const happyHi = "hiiiiii"; const twoHis = "hiihii"; const bye = "bye"; normalHi.match(zeroOrMoreOsRegex); // ["hi"] happyHi.match(zeroOrMoreOsRegex); // ["hiiiiii"] twoHis.match(zeroOrMoreOsRegex); // ["hii", "hii"] bye.match(zeroOrMoreOsRegex); // null ``` **惰性匹配** - 符合要求的字串的最短部分 - 預設情況下,正則表達式是貪婪匹配(滿足要求的字串的最長部分) - 使用 `?` 字元進行惰性匹配 ``` const testString = "catastrophe"; const greedyRexex = /c[a-z]*t/gi; const lazyRegex = /c[a-z]*?t/gi; testString.match(greedyRexex); // ["catast"] testString.match(lazyRegex); // ["cat"] ``` **匹配起始字串** - 要測試字串開頭的字元,請使用插入符 `^`,但要在字元集之外 ``` const emmaAtFrontOfString = "Emma likes cats a lot."; const emmaNotAtFrontOfString = "The cats Emma likes are fluffy."; const startingStringRegex = /^Emma/; startingStringRegex.test(emmaAtFrontOfString); // true startingStringRegex.test(emmaNotAtFrontOfString); // false ``` **匹配結尾字串** - 在正則表達式末尾使用美元符號 `$` 來檢查字串末尾是否匹配 ``` const emmaAtBackOfString = "The cats do not like Emma"; const emmaNotAtBackOfString = "Emma loves the cats"; const startingStringRegex = /Emma$/; startingStringRegex.test(emmaAtBackOfString); // true startingStringRegex.test(emmaNotAtBackOfString); // false ``` **匹配所有字母和數字** - 使用 `\w` 簡寫 ``` const longHand = /[A-Za-z0-9_]+/; const shortHand = /\w+/; const numbers = "42"; const myFavoriteColor = "magenta"; longHand.test(numbers); // true shortHand.test(numbers); // true longHand.test(myFavoriteColor); // true shortHand.test(myFavoriteColor); // true ``` **匹配除字母和數字以外的所有內容** - 你可以使用 `\w` 的反義詞也就是 `\W` ``` const noAlphaNumericCharRegex = /\W/gi; const weirdCharacters = "!_$!!"; const alphaNumericCharacters = "ab283AD"; noAlphaNumericCharRegex.test(weirdCharacters); // true noAlphaNumericCharRegex.test(alphaNumericCharacters); // false ``` **匹配所有數字** - 你可以使用字元集 `[0-9]`,或者使用簡寫形式 `\d` ``` const digitsRegex = /\d/g; const stringWithDigits = "My cat eats $20.00 worth of food a week."; stringWithDigits.match(digitsRegex); // ["2", "0", "0", "0"] ``` **匹配所有非數字** - 你可以使用 `\d` 的反義詞也就是 `\D` ``` const nonDigitsRegex = /\D/g; const stringWithLetters = "101 degrees"; stringWithLetters.match(nonDigitsRegex); // [" ", "d", "e", "g", "r", "e", "e", "s"] ``` **匹配空格** - 使用 `\s` 匹配空格和換行 ``` const sentenceWithWhitespace = "I like cats!" var spaceRegex = /\s/g; whiteSpace.match(sentenceWithWhitespace); // [" ", " "] ``` **匹配非空格** - 你可以使用 `\s` 的反義詞也就是 `\S` ``` const sentenceWithWhitespace = "C a t" const nonWhiteSpaceRegex = /\S/g; sentenceWithWhitespace.match(nonWhiteSpaceRegex); // ["C", "a", "t"] ``` **匹配字元數** - 您可以使用 `{lowerBound, upperBound}` 在一行中指定特定數量的字元 ``` const regularHi = "hi"; const mediocreHi = "hiii"; const superExcitedHey = "heeeeyyyyy!!!"; const excitedRegex = /hi{1,4}/; excitedRegex.test(regularHi); // true excitedRegex.test(mediocreHi); // true excitedRegex.test(superExcitedHey); //false ``` **匹配最少的字元數** - 您可以使用 `{lowerBound,}` 要求滿足最少數量的字元 - 這稱為數量說明符 ``` const regularHi = "hi"; const mediocreHi = "hiii"; const superExcitedHey = "heeeeyyyyy!!!"; const excitedRegex = /hi{2,}/; excitedRegex.test(regularHi); // false excitedRegex.test(mediocreHi); // true excitedRegex.test(superExcitedHey); //false ``` **匹配準確的字元數** - 您可以使用 `{requiredCount}` 指定要求字元數 ``` const regularHi = "hi"; const bestHi = "hii"; const mediocreHi = "hiii"; const excitedRegex = /hi{2}/; excitedRegex.test(regularHi); // false excitedRegex.test(bestHi); // true excitedRegex.test(mediocreHi); //false ``` **某字元可以不出現** - 要允許某字元可以不出現,請使用 `?` ``` const britishSpelling = "colour"; const americanSpelling = "Color"; const languageRegex = /colou?r/i; languageRegex.test(britishSpelling); // true languageRegex.test(americanSpelling); // true ``` --- 以上是基礎用法&範例,方便工作時可以查閱!