🔍 搜尋結果:日期

🔍 搜尋結果:日期

如何讓 AI 融入您的使用者(Next.js、OpenAI、CopilotKit)

長話短說 ---- 在本文中,您將了解如何建立基於 AI 的行銷活動管理應用程式,該應用程式可讓您建立和分析廣告活動,從而使您能夠為您的業務做出正確的決策。 我們將介紹如何: - 使用 Next.js 建立 Web 應用程式, - 使用 CopilotKit 將 AI 助理整合到軟體應用程式中,以及 - 建立特定於操作的人工智慧副駕駛來處理應用程式中的各種任務。 - 建立一名競選經理 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9xqpz356qm79t90f1l87.gif) --- CopilotKit:建構應用內人工智慧副駕駛的框架 -------------------------- CopilotKit是一個[開源的AI副駕駛平台](https://github.com/CopilotKit/CopilotKit)。我們可以輕鬆地將強大的人工智慧整合到您的 React 應用程式中。 建造: - ChatBot:上下文感知的應用內聊天機器人,可以在應用程式內執行操作 💬 - CopilotTextArea:人工智慧驅動的文字字段,具有上下文感知自動完成和插入功能📝 - 聯合代理:應用程式內人工智慧代理,可以與您的應用程式和使用者互動🤖 ![https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3 .amazonaws.com%2Fuploads%2Farticles%2Fx3us3vc140aun0dvrdof.gif](https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx3us3vc140aun0dvrdof.gif) {% cta https://git.new/devtoarticle1 %} Star CopilotKit ⭐️ {% endcta %} --- 先決條件 ---- 要完全理解本教程,您需要對 React 或 Next.js 有基本的了解。 我們還將利用以下內容: - [Radix UI](https://www.radix-ui.com/) - 用於為應用程式建立可存取的 UI 元件。 - [OpenAI API 金鑰](https://platform.openai.com/api-keys)- 使我們能夠使用 GPT 模型執行各種任務。 - [CopilotKit](https://github.com/CopilotKit/CopilotKit) - 一個開源副駕駛框架,用於建立自訂 AI 聊天機器人、應用程式內 AI 代理程式和文字區域。 --- 專案設定和套件安裝 --------- 首先,透過在終端機中執行以下程式碼片段來建立 Next.js 應用程式: ``` npx create-next-app campaign-manager ``` 選擇您首選的配置設定。在本教學中,我們將使用 TypeScript 和 Next.js App Router。 ![Next.js 應用程式安裝](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xboujt60i6lpoaqgjyap.png) 接下來,將[Heroicons](https://www.npmjs.com/package/@heroicons/react) 、 [Radix UI](https://www.radix-ui.com/)及其原始元件安裝到專案中。 ``` npm install @heroicons/react @radix-ui/react-avatar @radix-ui/react-dialog @radix-ui/react-dropdown-menu @radix-ui/react-icons @radix-ui/react-label @radix-ui/react-popover @radix-ui/react-select @radix-ui/react-slot @radix-ui/react-tabs ``` 另外,安裝[Recharts 程式庫](https://recharts.org/en-US)(一個用於建立互動式圖表的 React 程式庫)以及以下實用程式套件: ``` npm install recharts class-variance-authority clsx cmdk date-fns lodash react-day-picker tailwind-merge tailwindcss-animate ``` 最後,安裝[CopilotKit 軟體套件](https://docs.copilotkit.ai/getting-started/quickstart-chatbot)。這些套件使 AI copilot 能夠從 React 狀態檢索資料並在應用程式中做出決策。 ``` npm install @copilotkit/react-ui @copilotkit/react-textarea @copilotkit/react-core @copilotkit/backend ``` 恭喜!您現在已準備好建立應用程式。 --- 使用 Next.js 建立 Campaign Manager 應用程式 ----------------------------------- 在本節中,我將引導您建立活動管理器應用程式的使用者介面。 首先,讓我們進行一些初始設定。 在`src`資料夾中建立一個`components`和`lib`資料夾。 ``` cd src mkdir components lib ``` 在**`lib`**資料夾中,我們將聲明應用程式的靜態類型和預設活動。因此,在**`lib`**資料夾中建立**`data.ts`**和**`types.ts`**檔案。 ``` cd lib touch data.ts type.ts ``` 將下面的程式碼片段複製到`type.ts`檔中。它聲明了活動屬性及其資料類型。 ``` export interface Campaign { id: string; objective?: | "brand-awareness" | "lead-generation" | "sales-conversion" | "website-traffic" | "engagement"; title: string; keywords: string; url: string; headline: string; description: string; budget: number; bidStrategy?: "manual-cpc" | "cpa" | "cpm"; bidAmount?: number; segment?: string; } ``` 為應用程式建立預設的行銷活動清單並將其複製到`data.ts`檔案中。 ``` import { Campaign } from "./types"; export let DEFAULT_CAMPAIGNS: Campaign[] = [ { id: "1", title: "CopilotKit", url: "https://www.copilotkit.ai", headline: "Copilot Kit - The Open-Source Copilot Framework", description: "Build, deploy, and operate fully custom AI Copilots. In-app AI chatbots, AI agents, AI Textareas and more.", budget: 10000, keywords: "AI, chatbot, open-source, copilot, framework", }, { id: "2", title: "EcoHome Essentials", url: "https://www.ecohomeessentials.com", headline: "Sustainable Living Made Easy", description: "Discover our eco-friendly products that make sustainable living effortless. Shop now for green alternatives!", budget: 7500, keywords: "eco-friendly, sustainable, green products, home essentials", }, { id: "3", title: "TechGear Solutions", url: "https://www.techgearsolutions.com", headline: "Innovative Tech for the Modern World", description: "Find the latest gadgets and tech solutions. Upgrade your life with smart technology today!", budget: 12000, keywords: "tech, gadgets, innovative, modern, electronics", }, { id: "4", title: "Global Travels", url: "https://www.globaltravels.com", headline: "Travel the World with Confidence", description: "Experience bespoke travel packages tailored to your dreams. Luxury, adventure, relaxation—your journey starts here.", budget: 20000, keywords: "travel, luxury, adventure, tours, global", }, { id: "5", title: "FreshFit Meals", url: "https://www.freshfitmeals.com", headline: "Healthy Eating, Simplified", description: "Nutritious, delicious meals delivered to your door. Eating well has never been easier or tastier.", budget: 5000, keywords: "healthy, meals, nutrition, delivery, fit", }, ]; ``` 由於我們使用 Radix UI 建立可以使用 TailwindCSS 輕鬆自訂的基本 UI 元件,因此請在**`lib`**資料夾中建立一個**`utils.ts`**文件,並將以下程式碼片段複製到該文件中。 ``` //👉🏻 The lib folder now contains 3 files - data.ts, type.ts, util.ts //👇🏻 Copy the code below into the "lib/util.ts" file. import { type ClassValue, clsx } from "clsx"; import { twMerge } from "tailwind-merge"; export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)); } export function randomId() { return Math.random().toString(36).substring(2, 15); } ``` 導航到`components`資料夾並在其中建立其他三個資料夾。 ``` cd components mkdir app dashboard ui ``` `components/app`資料夾將包含應用程式中使用的各種元件,而儀表板資料夾包含某些元素的 UI 元件。 `ui`資料夾包含使用 Radix UI 建立的多個 UI 元素。將[專案儲存庫中的這些元素](https://github.com/CopilotKit/campaign-manager-demo/tree/main/src/components/ui)複製到該資料夾中。 恭喜! `ui`資料夾應包含必要的 UI 元素。現在,我們可以使用它們來建立應用程式中所需的各種元件。 ### 建立應用程式 UI 元件 在這裡,我將引導您完成為應用程式建立使用者介面的過程。 ![應用程式使用者介面](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9l4lvv4394gg033oatwq.png) 首先,導航至**`app/page.tsx`**檔案並將以下程式碼片段貼到其中。該文件呈現在**`components/app`**資料夾中聲明的 App 元件。 ``` "use client"; import { App } from "@/components/app/App"; export default function DashboardPage() { return <App />; } ``` 在`components/app`資料夾中建立`App.tsx` 、 `CampaignForm.tsx` 、 `MainNav.tsx`和`UserNav.tsx`檔案。 ``` cd components/app touch App.tsx CampaignForm.tsx MainNav.tsx UserNav.tsx ``` 將下面的程式碼片段複製到`App.tsx`檔案中。 ``` "use client"; import { DEFAULT_CAMPAIGNS } from "@/lib/data"; import { Campaign } from "@/lib/types"; import { randomId } from "@/lib/utils"; import { Dashboard } from "../dashboard/Dashboard"; import { CampaignForm } from "./CampaignForm"; import { useState } from "react"; import _ from "lodash"; export function App() { //👇🏻 default segments const [segments, setSegments] = useState<string[]>([ "Millennials/Female/Urban", "Parents/30s/Suburbs", "Seniors/Female/Rural", "Professionals/40s/Midwest", "Gamers/Male", ]); const [campaigns, setCampaigns] = useState<Campaign[]>( _.cloneDeep(DEFAULT_CAMPAIGNS) ); //👇🏻 updates campaign list function saveCampaign(campaign: Campaign) { //👇🏻 newly created campaign if (campaign.id === "") { campaign.id = randomId(); setCampaigns([campaign, ...campaigns]); } else { //👇🏻 existing campaign - search for the campaign and updates the campaign list const index = campaigns.findIndex((c) => c.id === campaign.id); if (index === -1) { setCampaigns([...campaigns, campaign]); } else { campaigns[index] = campaign; setCampaigns([...campaigns]); } } } const [currentCampaign, setCurrentCampaign] = useState<Campaign | undefined>( undefined ); return ( <div className='relative'> <CampaignForm segments={segments} currentCampaign={currentCampaign} setCurrentCampaign={setCurrentCampaign} saveCampaign={(campaign) => { if (campaign) { saveCampaign(campaign); } setCurrentCampaign(undefined); }} /> <Dashboard campaigns={campaigns} setCurrentCampaign={setCurrentCampaign} segments={segments} setSegments={setSegments} /> </div> ); } ``` - 從上面的程式碼片段來看, - 我為行銷活動建立了預設細分列表,並對已定義的行銷活動列表進行了深層複製。 - `saveCampaign`函數接受行銷活動作為參數。如果行銷活動沒有 ID,則表示它是新建立的,因此會將其新增至行銷活動清單。否則,它會找到該活動並更新其屬性。 - `Dashboard`和`CampaignForm`元件接受細分和行銷活動作為 props。 [Dashboard 元件](https://github.com/CopilotKit/campaign-manager-demo/blob/main/src/components/dashboard/Dashboard.tsx)在儀表板上顯示各種 UI 元素,而[CampaignForm 元件](https://github.com/CopilotKit/campaign-manager-demo/blob/main/src/components/app/CampaignForm.tsx)使用戶能夠在應用程式中建立和保存新的行銷活動。 您也可以使用[GitHub 儲存庫](https://github.com/CopilotKit/campaign-manager-demo/tree/main/src/components)中的程式碼片段來更新儀表板和應用程式元件。 恭喜!您應該有一個有效的 Web 應用程式,可讓使用者查看和建立新的行銷活動。 在接下來的部分中,您將了解如何將 CopilotKit 加入到應用程式中,以根據每個行銷活動的目標和預算進行分析和決策。 ![應用概述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4phyaucli8pdcbe625u4.gif) --- 使用 CopilotKit 透過 AI 分析廣告活動 -------------------------- 在這裡,您將學習如何將人工智慧加入到應用程式中,以幫助您分析行銷活動並做出最佳決策。 在繼續之前,請造訪[OpenAI 開發者平台](https://platform.openai.com/api-keys)並建立一個新的金鑰。 ![取得 OpenAI API 金鑰](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/02972pt2aj3kf9l5suqq.png) 建立一個`.env.local`檔案並將新建立的金鑰複製到該檔案中。 ``` OPENAI_API_KEY=<YOUR_OPENAI_SECRET_KEY> OPENAI_MODEL=gpt-4-1106-preview ``` 接下來,您需要為 CopilotKit 建立 API 端點。在 Next.js 應用程式資料夾中,建立一個包含`route.ts`檔案的`api/copilotkit`資料夾。 ``` cd app mkdir api && cd api mkdir copilotkit && cd copilotkit touch route.ts ``` 將下面的程式碼片段複製到`route.ts`檔中。 [CopilotKit 後端](https://docs.copilotkit.ai/reference/CopilotBackend)接受使用者的請求並使用 OpenAI 模型做出決策。 ``` import { CopilotBackend, OpenAIAdapter } from "@copilotkit/backend"; export const runtime = "edge"; export async function POST(req: Request): Promise<Response> { const copilotKit = new CopilotBackend({}); const openaiModel = process.env["OPENAI_MODEL"]; return copilotKit.response(req, new OpenAIAdapter({ model: openaiModel })); } ``` 若要將您的應用程式連接到此 API 端點,請更新`app/page.tsx`文件,如下所示: ``` "use client"; import { App } from "@/components/app/App"; import { CopilotKit } from "@copilotkit/react-core"; import { CopilotSidebar } from "@copilotkit/react-ui"; export default function DashboardPage() { return ( <CopilotKit url='/api/copilotkit/'> <CopilotSidebar instructions='Help the user create and manage ad campaigns.' defaultOpen={true} labels={{ title: "Campaign Manager Copilot", initial: "Hello there! I can help you manage your ad campaigns. What campaign would you like to work on?", }} clickOutsideToClose={false} > <App /> </CopilotSidebar> </CopilotKit> ); } ``` `CopilotKit`元件包裝整個應用程式並接受包含 API 端點連結的`url`屬性。 `CopilotSidebar`元件為應用程式加入了一個聊天機器人側邊欄面板,使我們能夠向 CopilotKit 提供各種指令。 ![將 CopilotKit 加入 Next.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wzh8ui253ftzmgtrcksd.gif) ### 如何讓AI副駕駛執行各種動作 CopilotKit 提供了兩個鉤子,使我們能夠處理使用者的請求並插入應用程式狀態: [useCopilotAction](https://docs.copilotkit.ai/reference/useCopilotAction)和[useMakeCopilotReadable](https://docs.copilotkit.ai/reference/useMakeCopilotReadable) 。 `useCopilotAction`掛鉤可讓您定義 CopilotKit 執行的動作。它接受包含以下參數的物件: - name - 操作的名稱。 - 描述 - 操作的描述。 - 參數 - 包含所需參數清單的陣列。 - render - 預設的自訂函數或字串。 - handler - 由操作觸發的可執行函數。 ``` useCopilotAction({ name: "sayHello", description: "Say hello to someone.", parameters: [ { name: "name", type: "string", description: "name of the person to say greet", }, ], render: "Process greeting message...", handler: async ({ name }) => { alert(`Hello, ${name}!`); }, }); ``` `useMakeCopilotReadable`掛鉤向 CopilotKit 提供應用程式狀態。 ``` import { useMakeCopilotReadable } from "@copilotkit/react-core"; const appState = ...; useMakeCopilotReadable(JSON.stringify(appState)); ``` CopilotKit 還允許您為使用者提示提供上下文,使其能夠做出充分且準確的決策。 將`guidance.ts`和`script.ts`加入到專案內的`lib`資料夾中,並將此[指導](https://github.com/CopilotKit/campaign-manager-demo/blob/main/src/lib/guideline.ts)和[腳本建議](https://github.com/CopilotKit/campaign-manager-demo/blob/main/src/lib/script.ts)複製到檔案中,以便 CopilotKit 做出決策。 在應用程式元件中,將當前日期、腳本建議和指導傳遞到 CopilotKit。 ``` import { GUIDELINE } from "@/lib/guideline"; import { SCRIPT_SUGGESTION } from "@/lib/script"; import { useCopilotAction, useMakeCopilotReadable, } from "@copilotkit/react-core"; export function App() { //-- 👉🏻 ...other component functions //👇🏻 Ground the Copilot with domain-specific knowledge for this use-case: marketing campaigns. useMakeCopilotReadable(GUIDELINE); useMakeCopilotReadable(SCRIPT_SUGGESTION); //👇🏻 Provide the Copilot with the current date. useMakeCopilotReadable("Today's date is " + new Date().toDateString()); return ( <div className='relative'> <CampaignForm segments={segments} currentCampaign={currentCampaign} setCurrentCampaign={setCurrentCampaign} saveCampaign={(campaign) => { if (campaign) { saveCampaign(campaign); } setCurrentCampaign(undefined); }} /> <Dashboard campaigns={campaigns} setCurrentCampaign={setCurrentCampaign} segments={segments} setSegments={setSegments} /> </div> ); } ``` 在`App`元件中建立一個 CopilotKit 操作,該操作可在使用者提供此類指令時建立新的活動或編輯現有的活動。 ``` useCopilotAction({ name: "updateCurrentCampaign", description: "Edit an existing campaign or create a new one. To update only a part of a campaign, provide the id of the campaign to edit and the new values only.", parameters: [ { name: "id", description: "The id of the campaign to edit. If empty, a new campaign will be created", type: "string", }, { name: "title", description: "The title of the campaign", type: "string", required: false, }, { name: "keywords", description: "Search keywords for the campaign", type: "string", required: false, }, { name: "url", description: "The URL to link the ad to. Most of the time, the user will provide this value, leave it empty unless asked by the user.", type: "string", required: false, }, { name: "headline", description: "The headline displayed in the ad. This should be a 5-10 words", type: "string", required: false, }, { name: "description", description: "The description displayed in the ad. This should be a short text", type: "string", required: false, }, { name: "budget", description: "The budget of the campaign", type: "number", required: false, }, { name: "objective", description: "The objective of the campaign", type: "string", enum: [ "brand-awareness", "lead-generation", "sales-conversion", "website-traffic", "engagement", ], }, { name: "bidStrategy", description: "The bid strategy of the campaign", type: "string", enum: ["manual-cpc", "cpa", "cpm"], required: false, }, { name: "bidAmount", description: "The bid amount of the campaign", type: "number", required: false, }, { name: "segment", description: "The segment of the campaign", type: "string", required: false, enum: segments, }, ], handler: (campaign) => { const newValue = _.assign( _.cloneDeep(currentCampaign), _.omitBy(campaign, _.isUndefined) ) as Campaign; setCurrentCampaign(newValue); }, render: (props) => { if (props.status === "complete") { return "Campaign updated successfully"; } else { return "Updating campaign"; } }, }); ``` {% 嵌入 https://www.youtube.com/watch?v=gCJpH6Tnj5g %} 新增另一個模擬 API 呼叫的操作,以允許 CopilotKit 從先前建立的活動中檢索歷史資料。 ``` // Provide this component's Copilot with the ability to retrieve historical cost data for certain keywords. // Will be called automatically when needed by the Copilot. useCopilotAction({ name: "retrieveHistoricalData", description: "Retrieve historical data for certain keywords", parameters: [ { name: "keywords", description: "The keywords to retrieve data for", type: "string", }, { name: "type", description: "The type of data to retrieve for the keywords.", type: "string", enum: ["CPM", "CPA", "CPC"], }, ], handler: async ({ type }) => { // fake an API call that retrieves historical data for cost for certain keywords based on campaign type (CPM, CPA, CPC) await new Promise((resolve) => setTimeout(resolve, 2000)); function getRandomValue(min: number, max: number) { return (Math.random() * (max - min) + min).toFixed(2); } if (type == "CPM") { return getRandomValue(0.5, 10); } else if (type == "CPA") { return getRandomValue(5, 100); } else if (type == "CPC") { return getRandomValue(0.2, 2); } }, render: (props) => { // Custom in-chat component rendering. Different components can be rendered based on the status of the action. let label = "Retrieving historical data ..."; if (props.args.type) { label = `Retrieving ${props.args.type} for keywords ...`; } if (props.status === "complete") { label = `Done retrieving ${props.args.type} for keywords.`; } const done = props.status === "complete"; return ( <div className=''> <div className=' w-full relative max-w-xs'> <div className='absolute inset-0 h-full w-full bg-gradient-to-r from-blue-500 to-teal-500 transform scale-[0.80] bg-red-500 rounded-full blur-3xl' /> <div className='relative shadow-xl bg-gray-900 border border-gray-800 px-4 py-8 h-full overflow-hidden rounded-2xl flex flex-col justify-end items-start'> <h1 className='font-bold text-sm text-white mb-4 relative z-50'> {label} </h1> <p className='font-normal text-base text-teal-200 mb-2 relative z-50 whitespace-pre'> {props.args.type && `Historical ${props.args.type}: ${props.result || "..."}`} </p> </div> </div> </div> ); }, }); ``` ![應用程式預覽](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kz3xm63ciq5q3kyooz9s.gif) 恭喜!您已完成本教學的專案。 結論 -- [CopilotKit](https://copilotkit.ai/)是一款令人難以置信的工具,可讓您在幾分鐘內將 AI Copilot 加入到您的產品中。無論您是對人工智慧聊天機器人和助理感興趣,還是對複雜任務的自動化感興趣,CopilotKit 都能讓您輕鬆實現。 如果您需要建立 AI 產品或將 AI 工具整合到您的軟體應用程式中,您應該考慮 CopilotKit。 您可以在 GitHub 上找到本教學的源程式碼: <https://github.com/CopilotKit/campaign-manager-demo> 感謝您的閱讀! --- 原文出處:https://dev.to/copilotkit/build-an-ai-powered-campaign-manager-nextjs-openai-copilotkit-59ii

終於明白響應式 UI 網頁設計了!

https://www.youtube.com/watch?v=qrl0h-gbafA 介紹 -- 在網路開發領域,響應式設計的概念通常會為初學者帶來陡峭的學習曲線。即使在轉向更高級的主題之後,許多人仍然難以完全掌握響應式設計的本質,而這一缺陷在他們的專案中變得明顯。 對許多工程師來說,響應式設計是一個難以實現的目標,主要是因為截止日期的緊迫感常常會將他們的注意力轉移到功能以及專案在個人裝置上的外觀上。這種狹隘的關注可能會導致對網站或應用程式在不同裝置上的執行情況的監督。 即使是成熟的網站也會在響應能力方面出現問題。就我個人而言,當我縮小筆記型電腦上的瀏覽器時,我發現眾所周知的 amazon.com 失去了美感。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w976yce0lip6ieikrvdv.jpg) 也就是說,我認為現在要達到相當熟練的響應式設計水平並不是太難。我只是認為教育界缺乏對這個主題的關注,也缺乏以清晰、全面的方式呈現它。這就是我打算在這篇文章/影片中做的事情。 我已經確定了為了實現幾乎所有響應式設計而必須了解的 7 個 CSS 屬性/概念。雖然可能還有其他技術可以增強反應能力,但這七種技術足夠全面,可以解決大多數情況。除非您的應用程式非常複雜,否則您應該能夠在合理的時間內理解並應用這些概念。 當然,要真正理解這些概念,實踐是不可或缺的。這就是為什麼我製作了一個影片教學來補充本指南,提供所討論原則的實際演示。請記住,隨著每次練習,這些概念都會變得更加直觀。 以下是我認為至關重要的主要主題: - 尺寸單位 - 相對於螢幕 - `vw` , `vh` - 相對於其他元素 - `%` - `max-width`和`min-width`屬性 - 彈性盒 - CSS 網格 - 媒體查詢 - 響應式影像屬性 - JavaScript 用於更複雜的回應行為 尺寸單位 ---- 大多數初學者專注於建立一個適合他們螢幕的設計。因此,他們沒有意識到以精確的方式(通常使用像素(px))指定元素的大小、填充、邊距等的缺點。問題是這些元素永遠不會隨著螢幕尺寸的變化而改變尺寸。過渡到使用較少的絕對單位,如百分比和視口單位 (vw/vh) 是靈活設計的關鍵。 ### 百分比 初學者必須小心百分比。理解父子關係的概念需要時間,當給子物件一個百分比時,它是其父/容器(可互換術語)大小的百分比,而不是整個螢幕的大小的百分比。 這裡的另一點是,所有看似「沒有父級」的外部元素實際上都有 - `<body>`元素。身體尺寸如下: - 寬度 - 螢幕的寬度 - Height - 其內部內容的高度(如果正文中沒有任何內容,則為 0) ### 視口寬度/高度 ( `vw` / `vh` ) 當您想要相對於*螢幕*調整元素的大小,從而與其*直接容器*的大小無關時,您需要使用`vw`和`vh` 。 下面是一個例子。假設您的網站應該有一個`<header>`然後是一個`<main>`部分,並且您想要專門調整標題的高度,並讓主要部分佔據螢幕的其餘高度。 實現此目的的一種方法如下: ``` header { height: 300px; } main { height: calc(100vh - 300px); } ``` 一個`vh`單位基本上是視口高度(螢幕高度)的 1%。因此, `100vh`表示螢幕高度的 100%,因此`calc(100vh - 300px)`表示「螢幕高度的 100% 減去 300px」。 這確保了主要部分將佔據標題之後螢幕的剩餘高度。 您也可以使用 flex 來實現此結果,但我稍後會討論這一點。在這種具體情況下,我認為兩者都可以。隨著專案複雜性的增加,也許一種方法會更好。 ### 何時使用 px 擁有這些其他選項以及我將在下面詳細介紹的選項絕對並不意味著 px 單位如今在 CSS 中沒有一席之地。在很多情況下,您希望某些東西具有不隨螢幕變化的特定尺寸。 UI 設計中的許多元素可能更喜歡永遠不會改變的特定尺寸。例如,按鈕的大小通常是這樣的。 `max-width`和`min-width`屬性 ------------------------- 當您希望元素的大小增大或縮小但僅限於某個點時,這些屬性會變得非常有用。 常見的情況是使用者介面頂部的搜尋欄。搜尋欄可能會佔據行動裝置上的大部分螢幕寬度。儘管筆記型電腦的搜尋欄比手機更大,但一旦裝置變大,您就不會希望搜尋欄幾乎保持全螢幕寬度。 看看 Airbnb 的輸入列如何隨著螢幕的增加而變化(我的意思是它的寬度)。 移動的: ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dmzs9j5c697xdh0z0a46.png) 藥片: ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ga7c6m2lmbyeyvqg2267.png) 大平板電腦/小筆記型電腦: ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p5khnujz7u4qovyvwyb9.png) 筆記型電腦: ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8mgnemzpbc5rm776xd9l.png) 這些影像有點難以判斷,但在行動裝置上,搜尋欄佔據了螢幕的大部分寬度,但就像素而言仍然很小。然後它擴展到平板電腦和小型筆記型電腦。但在某個時刻,隨著螢幕尺寸的進一步增大,它會停止增長。 彈性盒 --- 我覺得自己很幸運,在 Flexbox 發明之前不必學習 CSS。簡而言之,「Flex」是一種在位置和大小方面將元素相互關聯的驚人方法。 使用flex,你可以寫`display: flex;`在父元素上,那麼它就成為“彈性容器”,並且其所有直接子元素都成為“彈性專案”。您可以在 Flex 容器上設定幾個直覺的 Flex 相關屬性來描述 Flex 專案的行為。您也可以在 Flex 專案本身上設定一些屬性,以將其樣式與 Flex 專案的其餘部分區分開來。 初學者通常不理解彈性關係是嚴格在父子之間的。不是父母和孫子,等等。您可以擁有本身也是 Flex 容器的 Flex 專案。這意味著一個元素具有`display: flex;`它的子元素之一也有`display: flex;` 。 以下是 flex 可以派上用場的兩個最常見的場景: - Flex 可讓您在彼此相鄰或彼此之上的元素之間建立位置/空間關係。因此,例如,如果您在一行中有幾個專案,則只需使用一兩個簡單的 CSS 屬性即可在該行中將它們均勻地間隔開。 - 使用 flex,您可以輕鬆更改同級元素的定位方向。就方向而言,我的意思是從水平(行)到垂直(列),反之亦然。例如,考慮螢幕頂部導航中的連結,這些連結在移動設備的漢堡菜單下垂直組織。 CSS 網格 ------ Flex 有一個缺點,那就是當您嘗試同時控制兩個方向(x 軸和 y 軸)上的元素時。 Flex 的核心是為沿著同一個軸(x 軸或 y 軸)對齊的元素定義屬性。想要執行此操作的最常見場景是製作專案網格時。 當試圖確保它們的尺寸相同時,您可能會遇到麻煩。有關此範例,請參見下圖。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3kdcz1gzqzjrd68gncie.png) 使用網格,您只需應用一兩個簡單的 CSS 屬性即可,然後問題就解決了。見下文。 ``` #card-container { padding: 20px; display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 20px; justify-content: center; } ``` 注意 - 有些人實際上選擇在其網站的整個佈局中使用網格。說實話,我從來沒有花足夠的時間來探索這個選項,因為我先學了flex(網格後來出來了),而flex可以滿足我95%以上的需求。我確實只需要用於實際網格佈局的網格,如果我需要的話,它們通常是我網站的一部分。 在 UI 的不同部分使用 flex 和 grid 並沒有什麼問題! 媒體查詢 ---- 幾乎在任何設計中,當螢幕達到一定尺寸時,您都需要做出更大的改變。小螢幕更喜歡垂直滾動。使用更大的電腦螢幕,您可以水平放置更多元素。 透過媒體查詢,您可以定義所謂的“斷點”,即某些樣式將被覆蓋的點,以適應其他裝置的調整設計。 您可以選擇先建立行動用戶介面還是桌面使用者介面,然後建立一個斷點,在該斷點處定義新樣式以覆蓋最初並非針對的平台的現有樣式。 讓我們使用以下範例:對於行動設備,某些元素應組織在列中,但在較大的設備上,它們應組織在行中。 假設我們選擇了“行動優先設計”,這意味著首先設計行動用戶介面,然後確定實現更大設備設計的響應能力。這種選擇,而不是首先為筆記型電腦/桌上型電腦設計,在今天被認為更好,因為人們在手機上花費的時間比在大型電腦上花費的時間更多,而且公司更願意讓更多的用戶滿意。 好吧,告訴你的應用程式在平板電腦寬度和更大的情況下更改其外觀的方法基本上是- 使用媒體查詢斷點- 說,“在這個像素寬度和更高的像素寬度下,現在將這些專案的組織更改為一行。 此變更可能表示僅將 Flex 容器的 flex-direction 屬性從列變更為行,如下所示: ``` #flex-container { display: flex; flex-direction: column; } screen and (min-width: 768px) { #flex-container { flex-direction: row; } } ``` 此程式碼片段意味著 ID 為「flex-container」的元素將具有`flex-direction: column` ;對於寬度小於 768px 的螢幕,但對於寬度為 768px 及以上的螢幕,該元素將具有`flex-direction: row;` 。 附註 - 每個裝置都有相對標準的像素寬度,因此您可以尋找設定斷點的像素寬度,以指示從行動裝置到平板電腦、平板電腦到筆記型電腦等的轉換。 響應式圖像屬性 ------- 通常,上述屬性的組合將用於指定網站中圖像的大小,並且不需要進一步的 CSS。 然而,有時圖像不隨螢幕縮放。我想提供一些在這種情況發生時您可以探索的屬性。 其中一項屬性是`aspect-ratio` 。此屬性可讓您定義影像的首選縱橫比,以便它在不同的螢幕尺寸上始終保持相同的高寬比。 另一個屬性是`object-fit` ,它可以採用`fill` 、 `contain` 、 `cover` 、 `none`和`scale-down`等值,允許靈活控制圖像如何適應不同的螢幕尺寸。 JavaScript 用於更複雜的回應行為 --------------------- 最後,JS 在響應式設計中發揮著至關重要的作用,可以實現 CSS 單獨無法處理的更動態和複雜的調整,從而允許基於使用者互動或裝置規範的自訂行為。 使用 JS,您可以對更多事件類型做出反應,而不僅僅是螢幕尺寸更改,例如按鈕點擊、捲動、拖放等。 使用 JS,您可以編寫邏輯來根據您想要的任何條件動態調整元素的大小。例如,您可以根據使用者的裝置、行為、偏好和/或位置來調整內容。 JS 將佔 UI 程式碼的大部分,因此如果使用 HTML 和 CSS 無法輕鬆實現某些功能,則解決方案通常需要 JS。 結論 -- 實現響應式設計是一種平衡行為,需要將 CSS 技巧和策略性 JavaScript 結合起來。透過理解和應用上述七個關鍵概念,開發人員可以建立不僅具有視覺吸引力而且可適應所有必要設備的網站。 掌握響應式設計的旅程是不斷學習與實踐的過程。要了解這些概念的實際應用,請不要忘記查看隨附的影片教學。 請記住,響應式設計是觸手可及的,並且隨著每個專案的進行,該過程變得更加直觀。 希望我能夠透過這篇文章和影片使響應式設計成為一個不那麼模糊和令人畏懼的概念。 祝您未來的專案一切順利,感謝您的閱讀。 直到下一次, 賈里德 --- 原文出處:https://dev.to/jaredcodes/finally-understand-responsive-design-3con

🎁 100 倍速尋找開源專案的方法

今天,我提供了 **8 種方法**,可以幫助您找到 **夢想的開源專案**。 在深入研究如何找到開源專案的細節之前,讓我們先了解開源的含義。 ## 開源不僅僅是合併 PR 在我們聯繫比以往任何時候都更加緊密的世界中,成為開源社群的一部分可能是釋放新機會和實現個人成長的關鍵。 對我來說,這是一個無需工作就能做出改變的機會,對數百萬用戶產生影響。 你**編碼**。 **合作**。 **網路**。 但最重要的是,我們歡迎您,並且您一直與經驗豐富的人互動。 提示:為了長期利益,選擇好的組織而不是個人儲存庫。 --- 我已經提出了_200+ Pull Requests_並參與了_400多個討論_,所以我熟悉好的開源專案的要求和標準。 大多數人都在努力解決如何找到好的開源專案的問題。本文提供了許多適合您的選項。 --- ## 1. [GitHub 趨勢](https://github.com/trending) 您可以根據「口語」、「程式語言」和「日期」來尋找趨勢儲存庫。 這些都是可以提高您在開源社群中的可信度和聲譽的精英儲存庫。 - https://github.com/trending - 趨勢儲存庫 ![熱門 GitHub](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/03drf9tjt67gwsr7yfgz.png)   ## 2. [GitHub 進階篩選器](https://github.com/search?q=c%2B%2B&type=repositories) 如果您想完全控制搜尋,那麼此選項非常適合您。 您可以使用 60 多個選項進行過濾,包括“語言”、“星星數”、“分叉數”、“許可證”、“問題”,甚至“提交”。 ![進階過濾頁面](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/toohfew0pjd3ojd9bk0r.png)   ## 3. [Good First Issues](https://goodfirstissue.dev/) 如果您從開源開始,請不要使其變得更加複雜。 請記住,適合新貢獻者的問題通常被標記為“好第一個問題”或“需要幫助”,幫助您對開源做出第一個貢獻。 您可以透過友善的使用者介面選擇您喜歡的“語言”,從而找到幾個不錯的首要問題。 - https://goodfirstissue.dev - 好第一期 ![好第一期](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3faadrwr8bnujfhw13uf.png)   ## 4. [搶奪](https://up-for-grabs.net/) 該選項是尋找優秀開源專案的最受歡迎的網站之一。 您可以按“名稱”和“標籤”進行過濾,例如“good first issues”,並探索“流行標籤”,例如“opencv”和“android”。此外,您還可以檢查儲存庫上次更新的時間。 - https://up-for-grabs.net/ - 可供搶購 ![可供爭奪](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bsr83808vdwi3sot93qu.png)   ## 5. [首次貢獻](https://firstcontributions.github.io/) 一個網站,您可以使用您的首選“語言”作為過濾器從預定義列表中搜尋專案。 - https://firstcontributions.github.io/ - 第一個貢獻 ![首次貢獻](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9c3emvto8n69xgwrzjlw.png)   ## 6. [奎因](https://quine.sh/contribute) Quine 透過為開源做出貢獻,幫助您將聲譽貨幣化。他們有自己的排行榜、任務和許多創新功能。 您可以在不註冊的情況下搜尋專案,但我強烈建議您註冊並探索。 突出的功能是它顯示 PR 合併時間(以小時為單位),顯示當月有多少新貢獻者,並詳細說明問題類型。它提供了有關該專案的清晰想法。 - https://quine.sh/contribute - 奎因 ![奎因](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xp03znznmlaojz4j8gmr.png) 您甚至可以將小部件加入到您的個人資料中。那麼,繼續探索吧。 ![quine 小工具](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7f42an9lpirq9o6suve5.png)   ## 7. [OpenSauced](https://app.opensauced.pizza/) 有許多統計資料可以增加可信度,提供相關的過濾選項,例如「前 100 個儲存庫」、「最少 5 個貢獻者」、「最近」和「最活躍」。 您可以查看“PR 速度”和“PR 概述”,並使用語言或標籤進行過濾。 - https://app.opensauced.pizza/ - OpenSauced ![OpenSauced](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c5xzm8j37s92nz9yfb91.png) 在讓 Open Sauced 脫穎而出的所有功能中,它推薦了一些適合您的開源之旅的優秀儲存庫。 ![建議](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wfhkdarneeccba5rjw2a.png) 還有更多功能,例如建立突出顯示以追蹤所選儲存庫中的活動。   ## 8. [GSOC 組織](https://www.gsocorganizations.dev/) 根據我的經驗,我可以說為組織做出貢獻的好處遠遠超過個人儲存庫。 您一定聽過 Google Summer of Code,有信譽良好的組織參與其中。 在這裡,您可以探索 Google Summer of Code 中所有接受的組織的清單及其「技術堆疊」以及按「主題」和「類別」過濾的選項。 - https://www.gsocorganizations.dev/ - GSOC 組織 ![GSOC 組織](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eabd8qyf8rg976al93oe.png) --- > 如果您熱衷於贊助這篇文章,請給我發訊息 [email protected] 或在 Twitter 上聯繫我! 🚀 如果您有一些很棒的建議,請發表評論,我很樂意將它們加入到帖子中。 誰知道?您可能會發現新的熱情,結交終生的朋友,並實現超越您最瘋狂夢想的個人成長。因此,踏出第一步,為開源社群做出貢獻。世界在等你。 如果您喜歡我的內容,請在我的 GitHub 和 Twitter 上關注我以表達您的支持: - [GitHub](https://github.com/Anmol-Baranwal) - 繼續建造和創作! - [推特](https://twitter.com/Anmol_Codes) - [LinkedIn](https://www.linkedin.com/in/Anmol-Baranwal/) --- 原文出處:https://dev.to/anmolbaranwal/shortcut-to-find-open-source-projects-100x-faster-3lje

從頭開始實作 JavaScript 概念

在本文中,我們透過從頭開始建立幾個關鍵元件來探索 JavaScript 的基本建構塊。當我們深入研究這些概念時,我們將應用一系列從基礎到複雜的技術,使這種探索對於 JavaScript 世界的新手和專業人士都很有價值。 大綱 ---- - [`memoize()`](#memoize) - [`Array.map()`](#arraymap) - [`Array.filter()`](#arrayfilter) - [`Array.reduce()`](#arrayreduce) - [`bind()`](#bind) - [`call()` 、 `apply()`](#callapply) - [`setInterval()`](#setinterval) - [`cloneDeep()`](#clonedeep) - [`debounce()`](#debounce) - [`throttle()`](#throttle) - [`Promise`](#promise) - \[ `EventEmitter` ) <a name="memoize"></a> `memoize()` ----------- ### 任務說明 重新建立`memoize`函數(來自“lodash”),該函數透過快取函數呼叫的結果來優化效能。透過傳回快取的結果而不是重新計算,可以確保使用相同參數的重複函數呼叫更快。 ### 執行 ``` function customSerializer(entity, cache = new WeakSet()) { if (typeof entity !== 'object' || entity === null) { return `${typeof entity}:${entity}`; } if (cache.has(entity)) { return 'CircularReference'; } cache.add(entity); let objKeys = Object.keys(entity).sort(); let keyRepresentations = objKeys.map(key => `${customSerializer(key, cache)}:${ customSerializer(entity[key], cache) }` ); if (Array.isArray(entity)) { return `Array:[${keyRepresentations.join(',')}]`; } return `Object:{${keyRepresentations.join(',')}}`; } function myMemoize(fn) { const cache = new Map(); return function memoized(...args) { const keyRep = args.map(arg => customSerializer(arg) ).join('-'); const key = `${typeof this}:${this}-${keyRep}`; if (cache.has(key)) { return cache.get(key); } else { const result = fn.apply(this, args); cache.set(key, result); return result; } }; } ``` ### 實施的關鍵面 1. **快取機制:**它使用`Map`物件`cache`來儲存函數呼叫的結果。選擇`Map`物件是因為其高效率的鍵值配對和檢索功能。 2. **Custom Serializer** : `customSerializer`函數將函數參數轉換為用作快取鍵的字串表示形式。此序列化考慮了基本類型、物件(包括巢狀物件)、陣列和循環參考。對於物件和陣列,它們的鍵經過排序以確保一致的字串表示形式,無論屬性聲明順序如何。 3. **序列化`this`** : `this`的值指的是函數所屬的物件。在 JavaScript 中,方法可以根據呼叫它們的物件(即呼叫它們的上下文)而有不同的行為。這是因為`this`提供了對上下文物件的屬性和方法的存取,並且其值可能會根據函數的呼叫方式而變化。 4. **循環引用**:當物件直接或透過其屬性間接引用自身時,就會發生循環引用。這可能發生在更複雜的資料結構中,例如,物件`A`包含對物件`B`的引用,而物件`B`則直接或間接引用物件`A` 。處理循環引用以避免無限循環至關重要。 5. **使用`WeakSet`進行自動垃圾收集**: `WeakSet`保留對其物件的「弱」引用,這表示如果沒有其他引用, `WeakSet`中物件的存在不會阻止該物件被垃圾收集。此行為在需要臨時追蹤物件存在而又不會不必要地延長其生命週期的情況下特別有用。由於`customSerializer`函數可能只需要在序列化過程中標記物件的存取,而不儲存額外的資料,因此使用`WeakSet`可以確保物件不會僅僅因為它們在集合中的存在而保持活動狀態,從而防止潛在的內存洩漏。 <a name="arraymap"></a> `Array.map()` ------------- ### 任務說明 重新建立`Array.map()` ,它將轉換函數作為參數。此轉換函數將在陣列的每個元素上執行,並採用三個參數:當前元素、目前元素的索引和陣列本身。 ### 實施的關鍵面 1. **記憶體預先分配**: `new Array(this.length)`用於建立預先確定大小的陣列,以優化記憶體分配並透過避免加入元素時動態調整大小來提高效能。 ### 執行 ``` Array.prototype.myMap = function(fn) { const result = new Array(this.length); for (let i = 0; i < this.length; i++) { result[i] = fn(this[i], i, this); } return result; } ``` <a name="arrayfilter"></a> `Array.filter()` ---------------- ### 任務說明 重新建立`Array.filter()` ,它將謂詞函數作為輸入,迭代呼叫它的陣列的元素,將謂詞應用於每個元素。它傳回一個新陣列,僅包含謂詞函數傳回`true`元素。 ### 實施的關鍵面 1. **動態記憶體分配**:它動態地將符合條件的元素加入到`filteredArray`中,從而在很少有元素通過謂詞函數的情況下使該方法更有效地使用記憶體。 ### 執行 ``` Array.prototype.myFilter = function(pred) { const filteredArray = []; for (let i = 0; i < this.length; i++) { if (pred(this[i], i, this)) { filteredArray.push(this[i]); } } return filteredArray; } ``` <a name="arrayreduce"></a> `Array.reduce()` ---------------- ### 任務說明 重新建立`Array.reduce()` ,它對陣列的每個元素執行`reducer`函數,從而產生單一輸出值。 `reducer`函數有四個參數:累加器、currentValue、currentIndex 和整個陣列。 ### 實施的關鍵面 1. **`initialValue` value** : `accumulator`和`startIndex`會根據是否將`initialValue`作為參數傳遞來初始化。如果提供了`initialValue` (意味著`arguments.length`至少為`2` ),則`accumulator`設定為此`initialValue` ,並且迭代從第0個元素開始。否則,如果未提供`initialValue` ,則將陣列本身的第 0 個元素用作`initialValue` 。 ### 執行 ``` Array.prototype.myReduce = function(callback, initialValue) { let accumulator = arguments.length >= 2 ? initialValue : this[0]; let startIndex = arguments.length >= 2 ? 0 : 1; for (let i = startIndex; i < this.length; i++) { accumulator = callback(accumulator, this[i], i, this); } return accumulator; } ``` <a name="bind"></a> `bind()` -------- ### 任務說明 重新建立`bind()`函數,該函數允許將物件以及預先指定的初始參數(如果有)作為呼叫原始函數的上下文傳遞。它還應該支援`new`運算符的使用,從而能夠建立新實例,同時維護正確的原型鏈。 ### 執行 ``` Function.prototype.mybind = function(context, ...bindArgs) { const self = this; const boundFunction = function(...callArgs) { const isNewOperatorUsed = new.target !== undefined; const thisContext = isNewOperatorUsed ? this : context; return self.apply(thisContext, bindArgs.concat(callArgs)); }; if (self.prototype) { boundFunction.prototype = Object.create(self.prototype); } return boundFunction; }; ``` ### 實施的關鍵面 1. **處理`new` Operator** :語句`const isNewOperatorUsed = new.target !== undefined;`檢查是否透過`new`運算子將`boundFunction`作為建構函數呼叫。如果使用`new`運算符,則`thisContext`將設定為新建立的物件 ( `this` ) 而不是提供的`context` ,確認實例化應使用新的上下文而不是綁定期間提供的上下文。 2. **原型保留**:為了維護原始函數的原型鏈, `mybind`有條件地將`boundFunction`的原型設定為繼承自`self.prototype`的新物件。此步驟確保從`boundFunction` (用作建構函數時)建立的實例正確地繼承原始函數原型的屬性。此機制保留了預期的繼承層次結構並維護instanceof 檢查。 ### 將`bind()`與`new`一起使用的範例 讓我們考慮一個簡單的建構函數,它建立代表汽車的物件: ``` function Car(make, model, year) { this.make = make; this.model = model; this.year = year; } ``` 想像一下,我們常常創造「豐田」品牌的`Car`物件。為了讓這個過程更有效率,我們可以使用`bind`為Toyotas建立一個專門的建構函數,預先填入`make`參數: ``` // Creating a specialized Toyota constructor with 'Toyota' // as the pre-set 'make' const ToyotaConstructor = Car.bind(null, 'Toyota'); // Now, we can create Toyota car instances // without specifying 'make' const myCar = new ToyotaConstructor('Camry', 2020); // Output: Car { make: 'Toyota', model: 'Camry', year: 2020 } console.log(myCar); ``` <a name="callapply"></a> `call()` 、 `apply()` -------------------- ### 任務說明 重新建立`call()`和`apply()`函數,它們允許使用給定的 this 值和單獨提供的參數來呼叫函數。 ### 執行 ``` Function.prototype.myCall = function(context, ...args) { const fnSymbol = Symbol('fnSymbol'); context[fnSymbol] = this; const result = context[fnSymbol](...args); delete context[fnSymbol]; return result; }; Function.prototype.myApply = function(context, args) { const fnSymbol = Symbol('fnSymbol'); context[fnSymbol] = this; const result = context[fnSymbol](...args); delete context[fnSymbol]; return result; }; ``` ### 實施的關鍵面 1. **屬性命名的符號用法**:為了防止覆蓋上下文物件上潛在的現有屬性或由於名稱衝突而導致意外行為,使用唯一的`Symbol`作為屬性名稱。這確保了我們的臨時屬性不會幹擾上下文物件的原始屬性。 2. **執行後清理**:函數呼叫執行後,新增到上下文物件中的臨時屬性將被刪除。此清理步驟對於避免在上下文物件上留下修改後的狀態至關重要。 <a name="setinterval"></a> `setInterval()` --------------- ### 任務說明 使用`setTimeout`重新建立`setInterval` 。此函數應以指定的時間間隔重複呼叫提供的回呼函數。它會傳回一個函數,當呼叫該函數時,該函數會停止間隔。 ### 執行 ``` function mySetInterval(callback, interval) { let timerId; const repeater = () => { callback(); timerId = setTimeout(repeater, interval); }; repeater(); return () => { clearTimeout(timerId); }; } ``` ### 實施的關鍵面 1. **取消功能**: `mySetInterval`傳回的函數提供了一種簡單直接的方法來取消正在進行的間隔,而無需在函數範圍之外公開或管理計時器 ID。 <a name="clonedeep"></a> `cloneDeep()` ------------- ### 任務說明 重新建立執行給定輸入的深度複製的`cloneDeep`函數(來自“lodash”)。該函數應該能夠複製複雜的資料結構,包括物件、陣列、映射、集合、日期和正規表示式,並保持每個元素的結構和類型完整性。 ### 執行 ``` function myCloneDeep(entity, map = new WeakMap()) { if (entity === null || typeof entity !== 'object') { return entity; } if (map.has(entity)) { return map.get(entity); } let cloned; switch (true) { case Array.isArray(entity): cloned = []; map.set(entity, cloned); cloned = entity.map(item => myCloneDeep(item, map)); break; case entity instanceof Date: cloned = new Date(entity.getTime()); break; case entity instanceof Map: cloned = new Map(Array.from(entity.entries(), ([key, val]) => [myCloneDeep(key, map), myCloneDeep(val, map)])); break; case entity instanceof Set: cloned = new Set(Array.from(entity.values(), val => myCloneDeep(val, map))); break; case entity instanceof RegExp: cloned = new RegExp(entity.source, entity.flags); break; default: cloned = Object.create( Object.getPrototypeOf(entity)); map.set(entity, cloned); for (let key in entity) { if (entity.hasOwnProperty(key)) { cloned[key] = myCloneDeep(entity[key], map); } } } return cloned; } ``` ### 實施的關鍵面 1. **循環引用處理**:利用`WeakMap`來追蹤已存取的物件。如果遇到已經克隆的物件,則返回先前克隆的物件,有效處理循環參考並防止堆疊溢位錯誤。 2. **特殊物件的處理**:區分幾種物件類型( `Array` 、 `Date` 、 `Map` 、 `Sets` 、 `RegExp` ),以確保每種類型都被適當地克隆,並保留其特定特徵。 ``` - **`Array`**: Recursively clones each element, ensuring deep cloning. ``` ``` - **`Date`**: Copies the date using its numeric value (timestamp). ``` ``` - **Maps and Sets**: Constructs a new instance, recursively cloning each entry (for `Map`) or value (for `Set`). ``` ``` - **`RegExp`**: Clones by creating a new instance with the source and flags of the original. ``` 3. **物件屬性的複製**:當輸入是普通物件時,它會建立一個與原始物件具有相同原型的物件,然後遞歸地複製每個自己的屬性,在保持原型鏈的同時確保深度克隆。 4. **效率和性能**:利用`WeakMap`進行記憶,有效處理具有重複引用和循環的複雜大型結構,透過避免冗餘克隆來確保最佳性能。 <a name="debounce"></a> `debounce()` ------------ ### 任務說明 重新建立`debounce`函數(來自“lodash”),它允許限制給定回調函數觸發的頻率。當在短時間內重複呼叫時,在指定的延遲後僅執行最後一次呼叫。 ``` function myDebounce(func, delay) { let timerId; const debounced = function(...args) { clearTimeout(timerId); timerId = setTimeout(() => { func.apply(this, args); }, delay); }; debounced.cancel = function() { clearTimeout(timerId); timerId = null; }; debounced.flush = function() { clearTimeout(timerId); func.apply(this, arguments); timerId = null; }; return debounced; } ``` ### 實施的關鍵面 1. **取消功能**:引入`.cancel`方法使外部控制能夠取消去抖函數的任何暫停執行。這增加了靈活性,允許響應特定事件或條件而取消去抖功能。 2. **透過 Flush 立即執行**: `.flush`方法允許立即執行去抖函數,而不考慮延遲。這在需要確保立即應用去抖函數的效果的情況下非常有用,例如,在卸載元件或完成互動之前。 <a name="throttle"></a> `throttle()` ------------ ### 任務說明 重新建立`throttle`函數(來自“lodash”),它確保給定的回調函數在每個指定的時間間隔內最多只呼叫一次(在我們的例子中是在開始時)。與去抖動不同,限制保證函數會定期執行,確保進行更新,儘管更新速度是受控的。 ### 執行 ``` function myThrottle(func, timeout) { let timerId = null; const throttled = function(...args) { if (timerId === null) { func.apply(this, args) timerId = setTimeout(() => { timerId = null; }, timeout) } } throttled.cancel = function() { clearTimeout(timerId); timerId = null; }; return throttled; } ``` ### 實施的關鍵面 1. **取消功能**:引入`.cancel`方法可以清除節流計時器的任何計劃重置。這在清理階段非常有用,例如 UI 庫/框架中的元件卸載,以防止過時的執行並有效管理資源。 <a name="promise"></a> `Promise` --------- ### 任務說明 重新建立`Promise`類別。它是為非同步程式設計的構造,允許暫停程式碼的執行,直到非同步進程完成。從本質上講,承諾代表了在其建立時不一定已知的值的代理。它允許您將處理程序與非同步操作的最終成功值或失敗原因相關聯。這使得非同步方法可以像同步方法一樣傳回值:非同步方法不是立即傳回最終值,而是傳回一個在未來某個時刻提供該值的承諾。 `Promise`包含處理已完成和拒絕狀態的方法( `then` 、 `catch` ),以及無論結果如何都執行程式碼的方法( `finally` )。 ``` class MyPromise { constructor(executor) { ... } then(onFulfilled, onRejected) { ... } catch(onRejected) { ... } finally(callback) { ... } } ``` ### `constructor`實現 ``` constructor(executor) { this.state = 'pending'; this.value = undefined; this.reason = undefined; this.onFulfilledCallbacks = []; this.onRejectedCallbacks = []; const resolve = (value) => { if (this.state === 'pending') { this.state = 'fulfilled'; this.value = value; this.onFulfilledCallbacks.forEach(fn => fn()); } }; const reject = (reason) => { if (this.state === 'pending') { this.state = 'rejected'; this.reason = reason; this.onRejectedCallbacks.forEach(fn => fn()); } }; try { executor(resolve, reject); } catch (error) { reject(error); } } ``` ### `constructor`實現的關鍵方面 1. **狀態管理**:以「待處理」狀態初始化。解決時切換為“已完成”,被拒絕時切換為“拒絕”。 2. **值和原因**:保存承諾的最終結果( `value` )或拒絕的原因( `reason` )。 - **處理非同步**:接受包含非同步操作的`executor`函數。 `executor`採用兩個函數, `resolve`和`reject` ,當呼叫它們時,將promise轉換到對應的狀態。 3. **回呼陣列**:維護回呼佇列( `onFulfilledCallbacks` 、 `onRejectedCallbacks` ),以用於等待解決或拒絕承諾的延遲操作。 ### `.then`實施 ``` resolvePromise(promise2, x, resolve, reject) { if (promise2 === x) { return reject(new TypeError( 'Chaining cycle detected for promise')); } if (x instanceof MyPromise) { x.then(resolve, reject); } else { resolve(x); } } then(onFulfilled, onRejected) { onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value; onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason; }; let promise2 = new MyPromise((resolve, reject) => { if (this.state === 'fulfilled') { setTimeout(() => { try { let x = onFulfilled(this.value); this.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }); } else if (this.state === 'rejected') { setTimeout(() => { try { let x = onRejected(this.reason); this.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }); } else if (this.state === 'pending') { this.onFulfilledCallbacks.push(() => { setTimeout(() => { try { let x = onFulfilled(this.value); this.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }); }); this.onRejectedCallbacks.push(() => { setTimeout(() => { try { let x = onRejected(this.reason); this.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }); }); } }); return promise2; } ``` ### `.then`實施的關鍵方面 1. **預設處理程序**:將非函數處理程序轉換為標識函數(用於實現)或拋出程序(用於拒絕),以確保承諾鏈中的正確轉發和錯誤處理。 2. **Promise 連結**: `then`方法允許連結 Promise,從而實現順序非同步操作。它會建立一個新的 Promise ( `promise2` ),該 Promise 取決於傳遞給它的回呼函數 ( `onFulfilled` 、 `onRejected` ) 的結果。 3. **處理解決方案和拒絕**:僅在當前承諾解決(履行或拒絕)後才會呼叫所提供的回調。每個回呼的結果 ( `x` ) 可能是一個值或另一個 Promise,決定了`promise2`的解析。 4. **防止連結循環**: `resolvePromise`函數檢查`promise2`是否與結果 ( `x` ) 相同,避免 Promise 等待自身的循環,從而導致`TypeError` 。 5. **支援 MyPromise 和 Non-Promise 值**:如果結果 ( `x` ) 是`MyPromise`的實例, `then`使用其解析或拒絕來解決`promise2` 。此功能支援基於 Promise 的操作的無縫集成,無論是來自`MyPromise`實例還是本機 JavaScript Promise,假設它們具有相似的行為。對於非 Promise 值,或當`onFulfilled`或`onRejected`只是傳回一個值時, `promise2`將使用該值進行解析,從而在 Promise 鏈中實現簡單的轉換或分支邏輯。 6. **非同步執行保證**:透過使用`setTimeout`延遲`onFulfilled`和`onRejected`的執行, `then`確保非同步為。此延遲保持一致的執行順序,確保`onFulfilled`和`onRejected`在執行堆疊清除後呼叫。 7. **錯誤處理**:如果`onFulfilled`或`onRejected`內發生異常, `promise2`會因錯誤而被拒絕,從而允許錯誤處理通過 Promise 鏈傳播。 ### `catch`並`finally`實現 ``` static resolve(value) { if (value instanceof MyPromise) { return value; } return new MyPromise((resolve, reject) => resolve(value)); } catch(onRejected) { return this.then(null, onRejected); } finally(callback) { return this.then( value => MyPromise.resolve(callback()) .then(() => value), reason => MyPromise.resolve(callback()) .then(() => { throw reason; }) ); } ``` ### `.catch`實施的關鍵面向: 1. **簡化的錯誤處理:** `.catch`方法是`.then(null, onRejected)`的簡寫,專門專注於處理拒絕場景。當只需要拒絕處理程序時,它允許更清晰的語法,從而提高程式碼的可讀性和可維護性。 2. **Promise Chaining 支援:**由於它在內部委託給`.then` ,所以`.catch`返回一個新的 Promise,從而保持 Promise 鏈功能。這允許在錯誤恢復或透過重新拋出或返回新的被拒絕的承諾傳播錯誤後繼續進行鏈操作。 3. **錯誤傳播:**如果提供了`onRejected`並且執行時沒有錯誤,則傳回的 Promise 將使用`onRejected`的傳回值進行解析,從而有效地允許 Promise 鏈中的錯誤復原。如果`onRejected`拋出錯誤或傳回被拒絕的 Promise,則錯誤會沿著鏈傳播。 ### `.finally`實現的關鍵面向: 1. **始終執行:** `.finally`方法確保執行提供的`callback` ,無論 Promise 是履行還是拒絕。這對於需要在非同步操作之後發生的清理操作特別有用,與其結果無關。 2. **傳回值保留:**雖然`.finally`中的`callback`不接收任何參數(與`.then`或`.catch`不同),但 Promise 的原始履行值或拒絕原因將被保留並透過鏈傳遞。從`.finally`傳回的 Promise 會以相同的值或原因被解析或拒絕,除非`callback`本身導致被拒絕的 Promise。 3. **錯誤處理與傳播:**如果`callback`執行成功, `.finally`傳回的 Promise 將按照與原始 Promise 相同的方式進行結算。但是,如果`callback`拋出錯誤或返回被拒絕的 Promise,則從`.finally`返回的 Promise 會因這個新錯誤而被拒絕,從而允許錯誤攔截並更改 Promise 鏈中的拒絕原因。 <a name="eventemitter"></a> `EventEmitter` -------------- ### 任務說明 重新建立`EventEmitter`類,該類別允許實現觀察者模式,使物件(稱為「發射器」)能夠發出命名事件,從而導致呼叫先前註冊的偵聽器(或「處理程序」)。這是 Node.js 中用於處理非同步事件的關鍵元件,廣泛用於發出訊號以及管理應用程式狀態和行為。實作自訂`EventEmitter`涉及建立用於註冊事件偵聽器、觸發事件和刪除偵聽器的方法。 ``` class MyEventEmitter { constructor() { this.events = {}; } on(eventName, listener) { if (!this.events[eventName]) { this.events[eventName] = []; } this.events[eventName].push(listener); } once(eventName, listener) { const onceWrapper = (...args) => { listener.apply(this, args); this.off(eventName, onceWrapper); }; this.on(eventName, onceWrapper); } emit(eventName, ...args) { const listeners = this.events[eventName]; if (listeners && listeners.length) { listeners.forEach((listener) => { listener.apply(this, args); }); } } off(eventName, listenerToRemove) { if (!this.events[eventName]) { return; } const filterListeners = (listener) => listener !== listenerToRemove; this.events[eventName] = this.events[eventName].filter(filterListeners); } } ``` ### `EventEmitter`實現的關鍵面 1. **EventListener Registration `.on` :**將偵聽器函數新增至指定事件的偵聽器陣列中,如果該事件名稱尚不存在則建立一個新陣列。 2. **一次性事件偵聽器`.once` :**註冊一個偵聽器,該偵聽器在呼叫一次後會自行刪除。它將原始偵聽器包裝在一個函數 ( `onceWrapper` ) 中,該函數也會在執行後刪除包裝器,確保偵聽器僅觸發一次。 3. **發出事件`.emit` :**觸發事件,使用提供的參數呼叫所有已註冊的偵聽器。它將參數應用於每個偵聽器函數,從而允許將資料傳遞給偵聽器。 4. **刪除事件偵聽器`.off` :**從事件偵聽器陣列中刪除特定偵聽器。如果事件在刪除後沒有偵聽器,則可以將其保留為空陣列或可選地進一步清理(此實作中未顯示)。 --- 原文出處:https://dev.to/antonzo/implementing-javascript-concepts-from-scratch-4623

50 多個核心 Java 面試問題及程式設計師答案

--- 標題:針對程式設計師的 50 多個核心 Java 面試問題及其答案 發表:真實 描述:核心 Java 面試常見問題及其答案,幫助初學者和初級開發人員獲得第一份 Java 開發工作。 標籤: java、程式設計、職業 封面圖:https://thepracticaldev.s3.amazonaws.com/i/k63545lbbjmh582tiosr.png --- *揭露:這篇文章包含附屬連結;如果您透過本文中提供的不同連結購買產品或服務,我可能會獲得補償。* Java程式設計師大家好!在過去的幾年裡,我一直在分享許多[Java 面試問題](http://javarevisited.blogspot.sg/2015/10/133-java-interview-questions-answers-from-last-5-years.html)、答案和單獨討論。我的許多讀者要求我將他們聚集在一起,以便他們可以在同一個地方進行面試準備。 這篇文章就是這個結果。 本文包含**50 多個 Java 面試問題和答案**,涵蓋所有重要主題,如核心 Java 基礎知識、 [Java 集合框架](https://javarevisited.blogspot.com/2011/11/collection-interview-questions-answers.html)、 [Java 多執行緒和並發](https://javarevisited.blogspot.com/2014/07/top-50-java-multithreading-interview-questions-answers.html)、 [Java IO](https://javarevisited.blogspot.com/2014/08/socket-programming-networking-interview-questions-answers-Java.html) 、 [JDBC](https://javarevisited.blogspot.com/2012/12/top-10-jdbc-interview-questions-answers.html) 、 [JVM 內部原理](http://www.java67.com/2016/08/10-jvm-options-for-java-production-application.html)、 [編碼問題](http://www.java67.com/2018/06/data-structure-and-algorithm-interview-questions-programmers.html)、 [物件導向程式設計](http://www.java67.com/2015/12/top-30-oops-concept-interview-questions-answers-java.html)等。 這些問題是從我做過的各種 Java 訪談中挑選出來的,我的朋友、讀者和其他人根據自己的經驗分享了一些問題。它們絕不是非常困難。您可能已經在電話或面對面的面試中見過它們。 這些問題對於複習重要的 Java 主題(例如核心 Java 概念、多執行緒、lambda、流和集合)也非常有用。 我還分享了一些*用於進一步學習和提高的有用資源*,例如 Udemy 上的[**完整 Java 大師**](https://click.linksynergy.com/fs-bin/click?id=JVFxdTr9V80&subid=0&offerid=323058.1&type=10&tmpid=14538&RD_PARM1=https%3A%2F%2Fwww.udemy.com%2Fjava-the-complete-java-developer-course%2F)課程,您可以加入課程來提高和填補 Java 技能方面的空白。 我還寫過有關 Java 面試準備的書籍,例如[《Grokking the Java Interview》](https://gumroad.com/l/QqjGH)和[《Grokking the Spring Boot Interviews》](https://gumroad.com/l/hrUXKY) ,其中我為 Java 開發人員分享了很多問題。 如果你今年正在準備 Java 面試,你也可以**[在 Gumroad 上取得我的 Java + Spring Interview + SQL Bundle](https://javinpaul.gumroad.com/l/sowpfg)** ,使用程式碼**Friends20**還可獲得 20% 的折扣 [![Java 和 Spring 面試書籍](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xj0hpl0w5lyvdrnwlsoe.png)](https://javinpaul.gumroad.com/l/sowpfg) 那我們還在等什麼?以下是針對初學者和經驗豐富的 Java 開發人員的面試中最常見的一些 Java 問題的清單。 2 至 3 年經驗豐富的程式設計師的 50 個 Java 面試問題 --------------------------------- 因此,為了不浪費您的時間,這裡列出了一些針對初學者程式設計師的常見[核心 Java 面試問題](http://www.java67.com/2018/03/top-50-core-java-interview-questions.html)。此清單主要針對初學者和經驗不足的開發人員,例如具有 2 到 3 年 Java 經驗的人。 1) **Java如何實現平台無關性?** ([回答](http://www.java67.com/2012/08/how-java-achieves-platform-independence.html)) 提示:字節碼和Java虛擬機 答案 - Java 透過產生字節碼然後在 Java 虛擬機器上執行來實現平台獨立性,該虛擬機將這些字節碼轉換為依賴計劃的機器程式碼。由於不同平台的 JVM 不同,我的意思是,對於 Windows,您有單獨的 JRE(其中包括 JVM),對於 Linux,您將有單獨的 JRE。由於 Java 程式碼不會編譯為本機機器碼,而是編譯為字節碼,這使得它們獨立於平台。 2) **Java中的**`**ClassLoader**`**是什麼**? ([回答](http://javarevisited.blogspot.sg/2012/12/how-classloader-works-in-java.html#axzz59AWpr6cb)) 提示:JVM 的一部分,用於載入類別的字節碼。你可以自己寫。 答:在Java中,程式碼被封裝在類別中,因為Java是物件導向的程式設計。你的程式是在類別中寫的,為了執行它們,JVM 會載入這些包含你的程式碼的類別。負責載入類別的 JVM 元件稱為類別載入器。它們是存在的三個主要類別載入器:引導類別載入器、擴充類別載入器和應用程式類別載入器。 這是一個很好的圖表,顯示了每個 Java 類別載入器的功能: [![Java 中的類別載入器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g2brxfmzd67dv2k7rwmv.PNG)](https://javarevisited.blogspot.com/2021/05/java-classloader-interview.html) 3)**寫一個Java程式來檢查一個數字是偶數還是奇數?** ([回答](http://javarevisited.blogspot.sg/2013/04/how-to-check-if-number-is-even-or-odd.htm)) 提示:您可以使用位元運算符,例如位元與,記住,二進位格式中偶數末尾為 0,奇數末尾為 1。 4) **Java中**`**ArrayList**`**和**`**HashSet**`**的差別**? ([回答](http://www.java67.com/2012/07/difference-between-arraylist-hashset-in-java.html)) 提示: `List`和`Set`之間的所有差異都適用於此,例如排序、重複、隨機搜尋等。請參閱 Richard Warburton 的[**《Java 基礎知識:集合》**](https://pluralsight.pxf.io/c/1193463/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fcourses%2Fjava-fundamentals-collections)以了解有關Java 中的ArrayList、HashSet 和其他重要集合的更多資訊。 [![](https://miro.medium.com/max/875/1*hd861fcwDe86tY-1Y0VNRQ.png)](https://pluralsight.pxf.io/c/1193463/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fcourses%2Fjava-fundamentals-collections) 5)**什麼是單例中的雙重檢查鎖定?** ([回答](http://www.java67.com/2016/04/why-double-checked-locking-was-broken-before-java5.html)) 提示:兩次檢查實例是否已初始化,第一次不加鎖,第二次加鎖。 **6)如何在Java中建立線程安全的Singleton? (** [**回答**](http://javarevisited.blogspot.sg/2012/12/how-to-create-thread-safe-singleton-in-java-example.html)**)** 提示:有很多方法,例如使用 Enum 或使用雙重檢查鎖定模式或使用巢狀靜態類別。 **7) Java中Serialized和Externalized的差別? (** [**回答**](http://www.java67.com/2012/10/difference-between-serializable-vs-externalizable-interface.html)**)** 提示:Externalized 讓您可以更好地控制序列化過程。 **8) Java中何時使用瞬態變數? (**[**回答**](http://www.java67.com/2012/08/what-is-transient-variable-in-java.html)**)** 提示:當您想要在實作 Serialized 介面的類別中使變數不可序列化時。換句話說,您可以將其用於不想保存其值的變數。請參閱[**完整的 Java MasterClass**](https://click.linksynergy.com/fs-bin/click?id=JVFxdTr9V80&subid=0&offerid=323058.1&type=10&tmpid=14538&RD_PARM1=https%3A%2F%2Fwww.udemy.com%2Fjava-the-complete-java-developer-course%2F)以了解 Java 中的瞬態變數。 **9) Java中transient變數和volatile變數的差別? (** [**回答**](http://www.java67.com/2012/11/difference-between-transient-vs-volatile-modifier-variable-java.html)**)** 提示:完全不同,一個用於序列化上下文,另一個用於並發。 **10) Java中什麼時候使用易失性變數? (**[**回答**](http://www.java67.com/2012/08/what-is-volatile-variable-in-java-when.html)**)** 提示:當你需要指示JVM一個變數可以被多個執行緒修改並提示JVM不緩存其值。 **11)我們可以重寫Java中的私有方法嗎? (** [**回答**](http://www.java67.com/2013/08/can-we-override-private-method-in-java-inner-class.html)**)** 提示:不,因為它在子類別中不可見,這是在 Java 中重寫方法的主要要求。 12) **Java中**`**Hashtable**`**和**`**HashMap**`**的差別**? **(** [**回答**](http://javarevisited.blogspot.sg/2010/10/difference-between-hashmap-and.html#axzz53B6SD769)\*\*) \*\*提示:有幾個但最重要的是`Hashtable` ,它是同步的,而`HashMap`不是。與`HashMap`相比,它也是遺留的且緩慢的。 13) **Java中**`**List**`**和**`**Set**`**的差別**? **(** [**回答**](http://javarevisited.blogspot.sg/2012/04/difference-between-list-and-set-in-java.html#axzz53n9YK0Mb)**)** 提示: `List`是有序的並且允許重複。 `Set`是無序的,不允許有重複的元素。 14) **Java中**`**ArrayList**`**和**`**Vector**`**的區別**([**答案**](http://www.java67.com/2012/09/arraylist-vs-vector-in-java-interview.html)**)** 提示:很多,但最重要的是, `ArrayList`是非同步的,速度很快,而`Vector`是同步的,速度很慢。它也是像`Hashtable`這樣的遺留類別。 **15)** **Java 中**`**Hashtable**`**和**`**ConcurrentHashMap**`的差異? **(** [**回答**](http://javarevisited.blogspot.sg/2011/04/difference-between-concurrenthashmap.html#axzz4qw7RoNvw)**)** 提示:更具可擴展性。請參閱 Richard Warburton 的[**《Java 基礎知識:集合》**](https://pluralsight.pxf.io/c/1193463/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fcourses%2Fjava-fundamentals-collections)以了解更多資訊。 16) `**ConcurrentHashMap**`**如何實現可擴充性? (** [**回答**](http://javarevisited.blogspot.sg/2017/08/top-10-java-concurrenthashmap-interview.html#axzz50U9xyqbo)**)** 提示:透過將映射分為段並僅在寫入操作期間鎖定。 **17) 您將重寫哪兩個方法來將**`**Object**`**用作**`**HashMap**`**中的**`**Key**` **? (** [**回答**](http://www.java67.com/2013/06/how-get-method-of-hashmap-or-hashtable-works-internally.html)**)** 提示:等於和哈希碼 **18) Java中wait和sleep的差別? (**[**回答**](http://www.java67.com/2012/08/what-are-difference-between-wait-and.html)**)** \\ 提示: `wait()`方法釋放鎖定或監視器,而 sleep 則不會。 19\) **Java中**`**notify**`**和**`**notifyAll**`**的差別**? **(** [**回答**](http://www.java67.com/2013/03/difference-between-wait-vs-notify-vs-notifyAll-java-thread.html)**)** 提示: `notify`通知一個隨機執行緒正在等待該鎖,而`notifyAll`通知所有等待監視器的執行緒。如果你確定只有一個執行緒在等待,那麼使用`notify` ,否則`notifyAll`會更好。請參閱 Java Champion Heinz Kabutz 的[**線程基礎迷你課程,**](https://javaspecialists.teachable.com/p/threading-essentials/?product_id=539197&coupon_code=SLACK100?affcode=92815_johrd7r8)以了解有關線程基礎知識的更多資訊。 20\) 為什麼要**在 Java 中重寫 hashcode 以及**`**equals()**` ? **(** [**回答**](http://javarevisited.blogspot.sg/2015/01/why-override-equals-hashcode-or-tostring-java.html#axzz55oDxm8vv)**)** 提示:遵守 equals 和 hashcode 約定,如果您打算將物件儲存到集合類別(例如`HashMap`或`ArrayList`中,則需要遵守這一點。 21) `**HashMap**`**的負載因子是什麼意思? (**[**回答**](http://www.java67.com/2017/08/top-10-java-hashmap-interview-questions.html)**)** 提示:觸發`HashMap`調整大小的閾值一般為 0.75,這表示如果 HashMap 已滿 75%,則`HashMap`會自行調整大小。 **22)** **Java 中**`**ArrayList**`**和**`**LinkedList**`之間的差異? **(** [**回答**](http://www.java67.com/2012/12/difference-between-arraylist-vs-LinkedList-java.html)**)** 提示:與陣列和鍊錶相同,其中一個允許隨機搜尋,而另一種則不允許。在鍊錶上插入和刪除很容易,但在陣列上搜尋很容易。請參閱[**《Java 基礎知識:集合》**](https://pluralsight.pxf.io/c/1193463/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fcourses%2Fjava-fundamentals-collections) **(** Richard Warburton 在 Pluralsight 上的課程),以了解更多關於 Java 中基本集合資料結構的資訊。 **23)** **Java 中**`**CountDownLatch**`**和**`**CyclicBarrier**`之間的差異? **(** [**回答**](http://www.java67.com/2012/08/difference-between-countdownlatch-and-cyclicbarrier-java.html)**)** 提示:屏障被打破後,您可以重複使用`CyclicBarrier` ,但計數為零後,您無法重複使用`CountDownLatch` 。 24)**在 Java 中什麼時候使用**`**Runnable**`**和**`**Thread**` ? **(** [**回答**](http://www.java67.com/2016/01/7-differences-between-extends-thread-vs-implements-Runnable-java.html)**)** 提示:總是 **25) Java 中 Enum 類型安全的意義是什麼? (** [**回答**](http://www.java67.com/2014/04/what-java-developer-should-know-about-Enumeration-type-in-Java.html)**)** 提示:這表示您不能將不同 Enum 類型的實例指派給 Enum 變數。例如,如果您有一個像`DayOfWeek` day 這樣的變數,那麼您無法從`DayOfMonth`枚舉中為其指派值。 **26) Java 中整數的自動裝箱如何運作? (** [**回答**](http://javarevisited.blogspot.sg/2012/07/auto-boxing-and-unboxing-in-java-be.html#axzz59AWpr6cb)**)** 提示:透過使用Java中的`valueOf()`方法。 **27)** **Java 中**`**PATH**`**和**`**Classpath**`之間的差異? **(** [**回答**](http://www.java67.com/2012/08/what-is-path-and-classpath-in-java-difference.html)**)** 提示:作業系統使用`PATH` ,而JVM 使用`Classpath`來定位Java 二進位文件,例如JAR 檔案或Class 檔案。請參閱[**Java 基礎知識:核心平台**](https://pluralsight.pxf.io/c/1193463/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fcourses%2Fjava-fundamentals-core-platform),以了解有關`PATH` 、 `Classpath`和其他 Java 環境變數的更多資訊。 [![](https://miro.medium.com/max/478/1*PBuMgGmVXwBguv-SPw7YJw.jpeg)](https://pluralsight.pxf.io/c/1193463/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fcourses%2Fjava-fundamentals-core-platform) **28) Java中方法重載和重寫的差別? (** [**回答**](http://www.java67.com/2015/08/top-10-method-overloading-overriding-interview-questions-answers-java.html)**)** 提示:重寫發生在子類別中,而重載發生在同一個類別中。此外,覆蓋是執行時活動,而重載是在編譯時解決的。 **29) 如何防止 Java 中的類別被子類化? (**[**回答**](http://www.java67.com/2017/06/10-points-about-final-modifier-in-java.html)**)** \\ 提示:只需將其建構函數設為私有即可 **30) 你如何限制你的類別被你的客戶使用? (** [**回答**](http://javarevisited.blogspot.sg/2016/01/why-jpa-entity-or-hibernate-persistence-should-not-be-final-in-java.html)**)** \\ 提示:使建構子私有或從建構子拋出異常 **31)** **Java 中**`**StringBuilder**`**和**`**StringBuffer**`之間的差異? **(**[**回答**](http://www.java67.com/2016/10/5-difference-between-stringbuffer.html)**)** 提示: `StringBuilder`不同步,而`StringBuffer`同步。 **32) Java 中多態性與繼承的差別? (** [**回答**](http://www.java67.com/2014/04/difference-between-polymorphism-and-Inheritance-java-oops.html)**)** 提示:繼承允許程式碼重複使用並建構類別之間的關係,這是多態性所需要的,多態性提供動態行為。請參閱\[**物件導向的 Java 程式設計:資料結構及超越專業化**\]( https://coursera.pxf.io/c/3294490/1164545/14726?u=https%3A%2F%2Fwww.coursera.org%2Fspecializations%2Fjava-object-orientation)在Coursera 上,了解有關OOP 功能的更多資訊。適合初學者的最深入的課程之一。 \[![](https://thepracticaldev.s3.amazonaws.com/i/vuohxotp8qeh638lzjpr.png) \]( https://coursera.pxf.io/c/3294490/1164545/14726?u=https%3A%2F%2Fwww.coursera.org%2Fspecializations%2Fjava-物件導向) 順便說一句,如果您發現 Coursera 課程很有用,因為它們是由世界各地的知名公司和大學建立的,我建議您加入[**Coursera Plus**](https://coursera.pxf.io/c/3294490/1164545/14726?u=https%3A%2F%2Fwww.coursera.org%2Fcourseraplus) ,這是Coursera 的訂閱計劃,可以讓您無限制地存取他們最受歡迎的課程、專業、專業憑證和指導專案。它的費用約為 399 美元/年,但它完全物有所值,因為您可以獲得無限的憑證。 **33)我們可以在Java中重寫靜態方法嗎? (**[**回答**](http://www.java67.com/2012/08/can-we-override-static-method-in-java.html)**)** \\ 提示:否,因為重寫在執行時間解析,而靜態方法呼叫在編譯時解析。 **34) 我們可以存取Java中的私有方法嗎? (**[**回答**](http://www.java67.com/2012/08/can-we-override-private-method-in-java.html)**)** \\ 提示:可以,在同一個班級內,但不能在班級外 **35) Java中介面和抽象類別的區別? (** [**回答**](http://www.java67.com/2017/08/difference-between-abstract-class-and-interface-in-java8.html)**)** 提示:從[Java 8](https://dzone.com/articles/5-courses-to-crack-java-certification-ocajp-1z0-80)開始,差異變得模糊。然而,一個Java類別仍然可以實作多個接口,但只能擴展一個類別。 **36) Java 中 DOM 和 SAX 解析器的差別? (**[**回答**](http://www.java67.com/2012/09/dom-vs-sax-parser-in-java-xml-parsing.html)**)** \\ 提示:DOM 將整個 XML 檔案載入到記憶體中,而 SAX 則不會。它是一個基於事件的解析器,可用於解析大文件,但 DOM 速度很快,對於小文件應該是首選。 **37) Java 中 throw 和 throws 關鍵字的差異? (**[**回答**](http://www.java67.com/2012/10/difference-between-throw-vs-throws-in.html)**)** \\ 提示: throws 聲明方法在發生錯誤時可以拋出什麼異常,但 throw 關鍵字實際上會拋出異常。請參閱[**Java 基礎知識:異常處理**](https://pluralsight.pxf.io/c/1193463/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fcourses%2Fjava-fundamentals-exception-handling)以了解有關 Java 中異常處理的更多資訊。 [![](https://miro.medium.com/max/875/1*O5DEoN9mOy3D0HxFKWwfKQ.png)](https://pluralsight.pxf.io/c/1193463/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fcourses%2Fjava-fundamentals-exception-handling) **38) Java 中的故障安全迭代器和故障快速迭代器的差異? (** [**回答**](http://www.java67.com/2015/06/what-is-fail-safe-and-fail-fast-iterator-in-java.html)**)** 提示:故障安全性不會拋出`ConcurrentModificationException` ,而`fail-fast`則在迭代時檢測到底層集合的外部變更時拋出 ConcurrentModificationException。 **39) Java 中迭代器和枚舉的差別? (** [**回答**](http://javarevisited.blogspot.sg/2010/10/what-is-difference-between-enumeration.html#axzz59AWpr6cb)**)** 提示:迭代器還使您能夠在迭代時刪除元素,而枚舉不允許這樣做。 **40)** **Java 中的**`**IdentityHashMap**`是什麼? **(** [**回答**](http://www.java67.com/2016/09/difference-between-identityhashmap-weakhashmap-enummap-in-java.html)**)** 提示:一個`Map` ,它使用`==`相等運算子來檢查相等性,而不是`equals()`方法。 **41)** **Java 中的**`**String**`池是什麼? **(** [**回答**](http://javarevisited.blogspot.sg/2016/07/difference-in-string-pool-between-java6-java7.html#axzz4pGGwsyna)**)** 提示: `String`文字池。請記住,它已從 JDK 7 中的永久代空間移至堆疊。 **42)** Java 中`**Serializable**`**類別可以包含不可序列化欄位嗎? (** [**回答**](http://javarevisited.blogspot.sg/2016/09/how-to-serialize-object-in-java-serialization-example.html)\*\*) \*\*提示:是的,但您需要將其設定為靜態或瞬態。 **43) Java 中 this 和 super 的差別? (**[**回答**](http://www.java67.com/2013/06/difference-between-this-and-super-keyword-java.html)**)** 提示:this 指的是目前實例,而 super 指的是超類別的實例。 **44)** **Java 中**`**Comparator**`**和**`**Comparable**`之間的差異? **(** [**回答**](http://www.java67.com/2013/08/difference-between-comparator-and-comparable-in-java-interface-sorting.html)**)** \\ 提示: `Comparator`定義自訂排序,而`Comparable`定義物件的自然順序,例如`String`字母順序。請參閱[**完整的 Java 大師課程**](https://click.linksynergy.com/fs-bin/click?id=JVFxdTr9V80&subid=0&offerid=323058.1&type=10&tmpid=14538&RD_PARM1=https%3A%2F%2Fwww.udemy.com%2Fjava-the-complete-java-developer-course%2F)以了解有關 Java 排序的更多資訊。 [![](https://miro.medium.com/max/875/1*MTR8OytpiIMidLndBnsJ5g.png)](https://click.linksynergy.com/fs-bin/click?id=JVFxdTr9V80&subid=0&offerid=323058.1&type=10&tmpid=14538&RD_PARM1=https%3A%2F%2Fwww.udemy.com%2Fjava-the-complete-java-developer-course%2F) **45)** **Java 中**`**java.util.Date**`**和**`**java.sql.Date**`之間的差異? **(**[**回答**](http://javarevisited.blogspot.sg/2012/04/difference-between-javautildate-and.html)**)** 提示:前者包含日期和時間,後者僅包含日期部分。 46)為什麼**Java中的**`**Object**`類別**中宣告了wait和notify方法**? **(**[**回答**](http://javarevisited.blogspot.sg/2012/02/why-wait-notify-and-notifyall-is.html)**)** 提示:因為它們需要僅對物件可用的鎖。 **47)為什麼Java不支援多重繼承? (** [**回答**](http://javarevisited.blogspot.sg/2011/07/why-multiple-inheritances-are-not.html)**)** 提示:它不支持,因為 C++ 的體驗不好,但對於 Java 8,它在某種意義上是支援的 --- 現在 Java 中不支援`Type`的多重繼承。 **48) Java 中檢查異常和非檢查異常的差異? (** [**回答**](http://javarevisited.blogspot.sg/2011/12/checked-vs-unchecked-exception-in-java.html)**)** 提示:如果是選取的,則必須使用 catch 區塊處理異常,而如果是未選取的,則由您決定;編譯不會打擾你。 **49) Java 中錯誤和異常的區別? (**[**回答**](http://www.java67.com/2012/12/difference-between-error-vs-exception.html)**)** 提示:我厭倦了打字,請檢查答案 **50) Java 中的競爭條件和死鎖的差異? (** [**回答**](http://javarevisited.blogspot.sg/2012/02/what-is-race-condition-in.html#axzz59AbkWuk9)**)** 提示:這兩種錯誤都是並發應用程式中發生的錯誤,一種是由於執行緒調度而發生的,另一種是由於編碼不良而發生的。請參閱[Java 中的多執行緒和平行計算](https://click.linksynergy.com/fs-bin/click?id=JVFxdTr9V80&subid=0&offerid=323058.1&type=10&tmpid=14538&RD_PARM1=https%3A%2F%2Fwww.udemy.com%2Fmultithreading-and-parallel-computing-in-java%2F),以了解有關死鎖、競爭條件和其他多執行緒問題的更多資訊。 其他資源 --- - [Java 面試指南:200+ 面試題目及答案](https://click.linksynergy.com/fs-bin/click?id=JVFxdTr9V80&subid=0&offerid=323058.1&type=10&tmpid=14538&RD_PARM1=https%3A%2F%2Fwww.udemy.com%2Fjava-interview-questions-and-answers%2F) - [Spring框架面談指南---200+問答](https://click.linksynergy.com/fs-bin/click?id=JVFxdTr9V80&subid=0&offerid=323058.1&type=10&tmpid=14538&RD_PARM1=https%3A%2F%2Fwww.udemy.com%2Fspring-interview-questions-and-answers%2F) - [準備工作面試 作者:John Sonmez](https://pluralsight.pxf.io/c/1193463/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fcourses%2Fdeveloper-job-interviews) - [Markham 曝光的 Java 程式設計面試](http://www.amazon.com/Java-Programming-Interviews-Exposed-Markham/dp/1118722868?tag=javamysqlanta-20) - [破解編碼面試 --- 189 個問題和答案](http://www.amazon.com/Cracking-Coding-Interview-6th-Edition/dp/0984782850/?tag=javamysqlanta-20) - [求職面試的資料結構與演算法分析](https://click.linksynergy.com/fs-bin/click?id=JVFxdTr9V80&subid=0&offerid=323058.1&type=10&tmpid=14538&RD_PARM1=https%3A%2F%2Fwww.udemy.com%2Fdata-structure-and-algorithms-analysis%2F) - [過去 5 年 130 多道 Java 面試題](http://javarevisited.blogspot.sg/2015/10/133-java-interview-questions-answers-from-last-5-years.html) - [Grokking the Java Interview - 免費範例 PDF](https://javinpaul.gumroad.com/l/HMOAv) - [深入了解 Spring Boot 面試 - 免費 PDF 範本](https://javinpaul.gumroad.com/l/grokking-springboot-interview-sample) ### 結束語 謝謝,您已經讀到了文章的結尾...祝您程式設計面試順利!這當然不會很容易,但這些問題肯定會對您有所幫助。它還會鼓勵您了解更多。 如果您喜歡這篇文章,請與您的朋友和同事分享,並且不要忘記在 Twitter 上關注[javinpaul](https://twitter.com/javinpaul) ! > **PS ---**如果您需要一些免費資源來學習 Java,您可以查看[**我最喜歡的免費 Java 課程**](https://medium.com/javarevisited/10-free-courses-to-learn-java-in-2019-22d1f33a3915)清單來開始您的準備。 &gt; > **PSS ---**我沒有提供圖片中分享的面試問題的答案“程式碼中建立了多少個 String 物件?”你能猜出並解釋一下嗎? 而且,如果你今年正在準備 Java 面試,你還可以**[在 Gumroad 上取得我的 Java + Spring Interview + SQL Bundle](https://javinpaul.gumroad.com/l/sowpfg)** ,使用程式碼**friends20**也可以獲得 20% 的折扣 --- 原文出處:https://dev.to/javinpaul/50-core-java-interview-questions-with-answers-for-programmers-3bc

介紹 DEV 挑戰

我們正在開始一些特別的事情。它被稱為**DEV 挑戰**,這是一種參與社區、建立您的 DEV 檔案、獲得特殊徽章並享受樂趣的新方式。 **第一個挑戰將是前端挑戰**,將於下週三(3 月 20 日)宣布 - 請立即關注[\#devchallenge](/t/devchallenge) ,這樣您就不會錯過發布: {% 標籤 devchallenge %} 什麼是 DEV 挑戰? ----------- DEV 挑戰就像我們的[黑客馬拉鬆](https://dev.to/devteam/announcing-the-github-dev-2023-hackathon-4ocn)的微型版本,設計得更加靈活,有大量的參與機會。 挑戰將分為不同的領域,即*「前端挑戰」* 、 *「人工智慧挑戰」*等,並為您提供使用新工具累積經驗或向社區、潛在雇主公開展示您最佳技能的機會和更多。 每個 DEV 挑戰將持續約兩週,然後如果社區有興趣,挑戰將重新開始 - 有時使用相同的提示,有時使用新的提示。每個提示都小而平易近人,但提供了展示您的技能和創造力的機會。 我們可能會根據參與度和熱情開始和停止某些挑戰,如果我們相信新技術和合作夥伴關係對挑戰參與者和整個社區有利,我們將尋求引入新技術和合作夥伴關係。 參加挑戰意味著什麼? ---------- 輸入挑戰的方式是建立新的開發貼文並使用與該特定挑戰相關的標籤。我們將在提交過程中提供帖子模板,以便於輸入。 有什麼提示? ------ 挑戰提示會根據領域的不同而有所不同,但通常我們會要求您透過一個小型演示來展示您的創造力,或提供帖子格式的具體指南。有時它會提示您進行建置,有時它會提示您分享您的學習成果 - 無論哪種方式,我們都會獎勵您的創造力和熱情。 任何一周都*可能*進入前端挑戰賽的範例提示: - 創意十足的 CSS 藝術讓我們驚嘆不已 - 創造獨特、有用且美觀的 UI 元素 這些都是很一般的。有時我們會讓提示更具體: - 用 CSS 製作獨角獸 - 製作載入動畫 有時我們可能會出現愚蠢的提示: - 做出可以想像到的最糟糕的日期選擇器 獎品呢? ---- 獎品會因挑戰而異,有時甚至會根據提示而變化。與獎勵相關的所有細節將在具體的挑戰帖子中清楚地概述。 獎品將始終包括挑戰所特有的 DEV Profile 徽章。 雖然徽章將使您的開發者檔案更加美觀和獨特,但我們也將努力使這些徽章更加有用,作為為參與者打開專業大門的一種方式。雖然其中一部分是“只是為了好玩”,但我們相信參與並贏得挑戰可以幫助證明您在特定領域的技能。我們將尋求與能夠幫助您進一步參與 DEV 的組織合作。 除了徽章之外,獎品還包括商店優惠券和其他合作夥伴驅動的獎品(我們排列)。 你說夥伴? ----- 挑戰不會像我們社區範圍的黑客馬拉松通常那樣嚴格由合作夥伴驅動,但一些挑戰將包含合作夥伴組成部分,可能會附帶特殊贈品。 我們希望與合作夥伴合作,在獎品以及免費/折扣積分方面贊助某些挑戰,以建立他們的生態系統。 有些挑戰以及挑戰中的提示將具有強大的合作關係,而有些挑戰則根本沒有合作夥伴。 規則和常見問題解答 --------- 挑戰規則將在每個挑戰的說明中盡可能清楚地列出。有些規則適用於所有挑戰,有些則針對特定挑戰。雖然所有規則都符合我們的[一般條款](https://dev.to/terms)和[行為準則](https://dev.to/code-of-conduct),但以下幾點值得注意: #### **禁止抄襲…但允許對開放想法進行分叉和重複** 鼓勵模仿開源程式碼以及借鑒和改進想法,但任何被認為抄襲的內容都沒有資格獲得獎項。偶然的抄襲可能只會導致您被取消挑戰資格。嚴重的抄襲將導致您完全被 DEV 暫停。 riffing什麼時候變成抄襲了?這將取決於情況,但透明度很重要,許可證相容性也很重要。評審應該清楚你在程式碼和概念靈感方面加入到專案中的內容。 只要遵守所有其他規則**,人工智慧也是非常被允許的**。我們希望給您一個機會在現實的開發場景中展示您的技能。如果您使用人工智慧工具來幫助您完成提交,那麼一切權力都歸您所有。 #### *允許*重複參與。*允許*以過去的想法為基礎 我們有時會出現重複的提示,有時會出現新的提示。無論哪種方式,我們都鼓勵人們參與每項挑戰活動。如果參與者有資格提交新的提交內容,也歡迎他們在過去提交的內容的基礎上繼續進行。 如果您是在過去提交的基礎上進行的,則必須對自上次提交以來為改進參賽作品所做的工作保持透明,並且將根據當前挑戰的標準對您進行評判。我們希望這些挑戰成為繼續增強現有專案的機會,同時提供一個展示這項工作的新場所。 #### 評判是主觀的,你必須是個好的運動者 我們將制定一些評判的經驗法則,我們將盡力使比賽盡可能有趣,但您必須明白,評判參賽作品並不存在完美的方法。 我們將嘗試在一些規則上保持透明,例如:如果先前的獲勝者和新參與者之間的比分*非常接近*,我們將青睞新參與者。 這只是一些規則和說明的範例,我們相信社區秉承友好和包容性競爭的精神。 面向未來:自主挑戰 --------- 除了已經安排好的一切之外,我們還將提供以自定進度的方式參與挑戰的機會。也就是說,您將有機會在自己的時間完成挑戰並仍然獲得徽章,而不是按照嚴格的時間表提交並嘗試與社區其他成員一起贏得特定挑戰。 一旦我們推出了最初的幾個挑戰,我們將提供有關自定進度路徑的更多詳細資訊。 最後一件事 ----- Challenges 是我們今年春天推出的幾項新措施之一,旨在使 DEV 成為社區更加完整和充滿活力的生態系統。我們希望這裡的每個人都能有所收穫,並期待很快與大家分享更多內容。 問題? --- 如果我們在這裡沒有介紹任何內容,請隨時在評論中提出問題。否則,請繼續關注,我們希望在 3 月 X 日推出 CSS/前端挑戰時看到您加入其中。您現在可以關注標籤,以確保您不會錯過該帖子。 {% 標籤 devchallenge %} --- 原文出處:https://dev.to/devteam/introducing-dev-challenges-1mk9

給女性工程師:10 項增強女性科技能力的線上資源

長話短說 ---- 隨著 3 月 8 日的臨近,我總是會在這個時候反思我作為科技女性的經歷。 我從事科技工作已有五年多了。 我一開始是資料科學家,現在我正在探索並喜歡[Taipy](https://github.com/Avaiga/taipy)的 DevRel 🥑 角色。 不用說,科技領域的發展充滿了起起落落,以及介於兩者之間的一切。 ![性別差異](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/upvr60s75yue60ebdbff.png) 國際婦女節不僅僅是日曆上的一個日期;它也是一個節日。今天對我們來說至關重要,我們要思考如何改善情況。這是慶祝、反思和改變的一天! --- 這一天讓我質疑自己的進化。 儘管我必須克服冒名頂替症候群並不斷尋找歸屬感,但科技的進步是有益且令人興奮的。 然而,這些挑戰塑造了今天的我,並磨練了我最大的優勢。 在我的發展過程中,我在各種社區和資源中發現了令人難以置信的支持系統,我很高興與您分享: --- 社群 -- ### PyLadies ![皮拉迪斯](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a8uky29xpk6n2mfmge5l.png) 身為 Python 愛好者,Pyladies 在我心中佔有特殊的地位。我參加過他們在巴黎和倫敦舉行的聚會,他們也在全球 50 多個城市舉辦了活動。顧名思義,該小組是開源 Python 社群的活躍組成部分。一個了解 Python 最新趨勢的好地方,甚至可以透過他們的研討會提高您的編碼技能。 https://pyladies.com/ --- ### 機器學習和資料科學領域的女性 ![無線MLDS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aodbft8fk16d9mmcrj9p.png) 機器學習和資料科學領域的女性支持並促進有興趣在機器學習和資料科學領域取得進步的女性。 參加他們在法國和英國舉行的活動是了解最新趨勢並與其他資料科學愛好者交流的絕佳機會。 https://wimlds.org/ --- ### 科技女性 ![威特](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/inilre39c2idekq9bh2m.png) 這個全球組織致力於幫助女性擁抱科技。他們擁有全球視野,致力於賦權和縮小性別差距。 https://women-in-tech.org/ --- ### 編碼的女性 ![WWC](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z1av53wrxvufpn1vmttv.png) 旨在賦予女性技術職業權力。他們舉辦編碼活動和資源,專注於幫助女性走上職業道路。如果您覺得需要一些職業指導,請不要猶豫查看他們的網站。 https://womenwhocode.com/ --- 會議 -- ### 格蕾絲·霍珀慶祝活動 ![生長激素](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5qltssqxjnvsc40v98el.png) 聚集科技領域女性的最重要活動。該活動以一位鼓舞人心的電腦科學家的名字命名,展示了女性在電腦領域的職業和研究。 https://ghc.anitab.org/ --- ### 女性科技節 ![盛宴](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cggr6cyfcd9mzng2tdsf.png) 這是一個充滿活力的活動,透過鼓舞人心的演講、社交和研討會展示科技領域的女性。 https://ghc.anitab.org/ --- ### 資料和人工智慧領域的女性+ ![華加](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x4jf6of1jozopgqiqefa.png) 這是我去年最喜歡的會議之一。能量是 鼓舞人心-現代會議展示了代表性不足的性別在該領域的貢獻。 https://www.womenintechfestivalglobal.com/womenintechfestivalglobal2024/en/page/home --- podcast ------- ### 女性科技播客 ![特別是](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y6dl4vh8g6lalb3eo4if.png) 該播客將為您講述科技業女性的精彩故事,從她們的旅程到挑戰,以及一些精心建置的建議。 https://podcast.womenintechshow.com/ --- ### 科技女孩演員陣容 ![TC](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0ez1o0kwicb0urqt26ii.png) 另一個勵志播客,它將帶您了解女性的故事,並在日常生活中激勵您。 https://podcasts.apple.com/us/podcast/tech-girls-cast/id1557400427 --- ### She Talks Tech ![她說話](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8bppajq0h7sgs4zp0zsl.png) 該播客與該行業的主要女性進行了強有力的對話。它們涵蓋了領導力和個人成長等主題。 https://wearetechwomen.com/she-talks-tech-podcast/ --- 子版塊 --- ### /girlsgonewired ![有線](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/osdfsw36p2rm08vuuwj9.png) STEM 領域的女性和非二元性別社群。您可以分享您的故事並尋求建議。用作支援系統的 Reddit 子版塊。 https://www.reddit.com/r/girlsgonewired/ --- ### /女性科技 ![機智](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kyleoylj40cdebwb81ar.png) 這是一個很棒的 Reddit 子版塊,用於討論您在科技行業的經歷、挑戰和成就。在 Reddit 子版塊中閃耀並支持女性。 https://www.reddit.com/r/womenintech/ --- ### /科學女士們 ![女士們](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xcej49410cof23q1zaes.png) 這是一個為科技業女性提供支援的 Reddit 子版塊。您會找到證詞、建議和展示。 https://www.reddit.com/r/LadiesofScience/ --- 最後的想法 ----- 我的科技之旅既有時感覺自己像個局外人,又學著擁抱自己的優勢和獨特性。這些社區在這一演變中發揮了作用。 讓我們繼續打破障礙,確保科技世界具有包容性和歡迎性。 不要猶豫,在評論中分享您最喜歡的資源! --- 原文出處:https://dev.to/marisogo/10-resources-to-empower-women-in-technology-2m6n

100 多個專案創意

**編輯**:大家好!在對本文做出驚人反應後,我建立了一個名為「每週專案俱樂部」的專案。每週您的收件匣都會收到需要解決的問題。你可以努力解決問題,並且你將得到整個俱樂部的幫助,讓你走上正軌。了解更多並[在這裡](https://weeklyproject.club)註冊! 有一天我注意到一個模式。我注意到很多人都在努力 學習編程,但他們心中沒有特定的目標。我已經討論過如何了解您想要學習程式設計的原因可以幫助您選擇要學習的語言[!](https://pickaframework.com/articles/why/) ,以及如何實際做出決定([在這裡!](https://pickaframework.com/feature_fishing/) )但是專案有什麼幫助呢? 當我指導程式設計師時,我發現有一個專案可以幫助排除其他一些幹擾,例如想知道你是否使用了正確的語言。透過專注於一個特定的目標,你就不用那麼費力去擔心*這*是否正是你應該使用的語言。結果是你建立了一些簡潔的東西,並且一路上你學到了一些東西! 2隻鳥,1塊石頭。 這就是為什麼我為初學者程式設計師策劃了這個專案清單。許多人列出了大量的專案來學習編程,但很少按照難度進行組織。我瀏覽了幾個流行的程式設計專案想法清單。如果您想查看完整列表,可以在頁面底部找到來源。 我將其分為教程和想法。教程包含資源連結,而想法只是專案的一般描述。我還列出了我最喜歡的初學者清單。 看看,看看是否有什麼啟發你! 教學 == 我的最愛 ---- - [透過 30 個教學在 30 天內建立 30 個東西](https://javascript30.com) - [在 30 分鐘內建立一個簡單的搜尋機器人](https://medium.freecodecamp.org/how-to-build-a-simple-search-bot-in-30-minutes-eb56fcedcdb1) - [使用 Xamarin 和 Visual Studio 建立 iOS 照片庫應用程式](https://www.raywenderlich.com/134049/building-ios-apps-with-xamarin-and-visual-studio) - [建立 Android 手電筒應用程式](https://www.youtube.com/watch?v=dhWL4DC7Krs)(影片) - [製作聊天應用程式](https://medium.freecodecamp.org/how-to-build-a-chat-application-using-react-redux-redux-saga-and-web-sockets-47423e4bc21a) - [使用 React Native 建立 ToDo 應用程式](https://blog.hasura.io/tutorial-fullstack-react-native-with-graphql-and-authentication-18183d13373a) 簡單的 --- - [使用 C# 和 Xamarin 建立空白應用程式(正在進行中)](https://www.intertech.com/Blog/xamarin-tutorial-part-1-create-a-blank-app/) - [使用 Xamarin 和 Visual Studio 建立 iOS 照片庫應用程式](https://www.raywenderlich.com/134049/building-ios-apps-with-xamarin-and-visual-studio) - [建立加載畫面](https://medium.freecodecamp.org/how-to-build-a-delightful-loading-screen-in-5-minutes-847991da509f) - [使用 JS 建立 HTML 計算器](https://medium.freecodecamp.org/how-to-build-an-html-calculator-app-from-scratch-using-javascript-4454b8714b98) - [建立 React Native Todo 應用程式](https://egghead.io/courses/build-a-react-native-todo-application) - 使用 Node.js 編寫 Twitter 機器人 ``` - [Part 1](https://codeburst.io/build-a-simple-twitter-bot-with-node-js-in-just-38-lines-of-code-ed92db9eb078) ``` ``` - [Part 2](https://codeburst.io/build-a-simple-twitter-bot-with-node-js-part-2-do-more-2ef1e039715d) ``` - [建立一個簡單的 RESTFUL Web 應用程式](https://closebrace.com/tutorials/2017-03-02/creating-a-simple-restful-web-app-with-nodejs-express-and-mongodb) - [在 30 分鐘內建立一個簡單的搜尋機器人](https://medium.freecodecamp.org/how-to-build-a-simple-search-bot-in-30-minutes-eb56fcedcdb1) - [建立一個工作抓取 Web 應用程式](https://medium.freecodecamp.org/how-i-built-a-job-scraping-web-app-using-node-js-and-indreed-7fbba124bbdc) - [使用 Python 挖掘 Twitter 資料](https://marcobonzanini.com/2015/03/02/mining-twitter-data-with-python-part-1/) - [使用 Scrapy 和 MongoDB 抓取網站](https://realpython.com/blog/python/web-scraping-with-scrapy-and-mongodb/) - [如何使用 Python 和 Selenium WebDriver 進行抓取](http://www.byperth.com/2018/04/25/guide-web-scraping-101-what-you-need-to-know-and-how-to-scrape-with-python-selenium-webdriver/) - [我應該使用 BeautifulSoup 觀看哪部電影](https://medium.com/@nishantsahoo.in/which-movie-should-i-watch-5c83a3c0f5b1) - [使用 Flask 建立微博](https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world) - 在 Django 中建立部落格 Web 應用程式 ``` - [Part I : Introduction](https://tutorial.djangogirls.org/en/) ``` ``` - [Part II : Extension To Add More Features](https://legacy.gitbook.com/book/djangogirls/django-girls-tutorial-extensions/details) ``` - [選擇您自己的冒險演示](https://www.twilio.com/blog/2015/03/choose-your-own-adventures-presentations-wizard-mode-part-1-of-3.html) - [使用 Flask 和 RethinkDB 建立待辦事項列表](https://realpython.com/blog/python/rethink-flask-a-simple-todo-list-powered-by-flask-and-rethinkdb/) 中等的 --- - [透過建立簡單的 RPG 遊戲來學習 C#](http://scottlilly.com/learn-c-by-building-a-simple-rpg-index/) - [用 C# 創作 Rogue-like 遊戲](https://roguesharp.wordpress.com/) - [使用 Clojure 建構 Twitter 機器人](http://howistart.org/posts/clojure/1/index.html) - [建立拼字檢查器](https://bernhardwenzel.com/articles/clojure-spellchecker/) - [使用 Java 建立簡單的 HTTP 伺服器](http://javarevisited.blogspot.com/2015/06/how-to-create-http-server-in-java-serversocket-example.html) - [建立 Android 手電筒應用程式](https://www.youtube.com/watch?v=dhWL4DC7Krs)(影片) - [建立具有使用者身份驗證的 Spring Boot 應用程式](https://scotch.io/tutorials/build-a-spring-boot-app-with-user-authentication) - [透過 30 個教學在 30 天內建立 30 個東西](https://javascript30.com) - [使用純 JS 建立應用程式](https://medium.com/codingthesmartway-com-blog/pure-javascript-building-a-real-world-application-from-scratch-5213591cfcd6) - [建立無伺服器 React.js 應用程式](http://serverless-stack.com/) - [建立 Trello 克隆](http://codeloveandboards.com/blog/2016/01/04/trello-tribute-with-phoenix-and-react-pt-1/) - [使用 React、Node、MongoDB 和 SocketIO 建立角色投票應用程式](http://sahatyalkabov.com/create-a-character-voting-app-using-react-nodejs-mongodb-and-socketio/) - [React 教學:克隆 Yelp](https://www.fullstackreact.com/articles/react-tutorial-cloning-yelp/) - [使用 React.js 和 Node.js 建立簡單的中型克隆](https://codeburst.io/build-simple-medium-com-on-node-js-and-react-js-a278c5192f47) - [在 JS 中整合 MailChimp](https://medium.freecodecamp.org/how-to-integrate-mailchimp-in-a-javascript-web-app-2a889fb43f6f) - [使用 React Native 建立 ToDo 應用程式](https://blog.hasura.io/tutorial-fullstack-react-native-with-graphql-and-authentication-18183d13373a) - [製作聊天應用程式](https://medium.freecodecamp.org/how-to-build-a-chat-application-using-react-redux-redux-saga-and-web-sockets-47423e4bc21a) - [使用 React Native 建立新聞應用程式](https://medium.freecodecamp.org/create-a-news-app-using-react-native-ced249263627) - [學習 React 的 Webpack](https://medium.freecodecamp.org/learn-webpack-for-react-a36d4cac5060) - [建立您自己的 React 樣板](https://medium.freecodecamp.org/how-to-build-your-own-react-boilerplate-2f8cbbeb9b3f) - [基本 React+Redux 入門教學](https://hackernoon.com/a-basic-react-redux-introductory-tutorial-adcc681eeb5e) - [建立一個預約安排程序](https://hackernoon.com/build-an-appointment-scheduler-using-react-twilio-and-cosmic-js-95377f6d1040) - 使用 Angular 2+ 建立具有離線功能的 Hacker News 用戶端 ``` - [Part 1](https://houssein.me/angular2-hacker-news) ``` ``` - [Part 2](https://houssein.me/progressive-angular-applications) ``` - 帶有 Angular 5 的 ToDo 應用程式 ``` - [Introduction to Angular](http://www.discoversdk.com/blog/intro-to-angular-and-the-evolution-of-the-web) ``` ``` - [Part 1](http://www.discoversdk.com/blog/angular-5-to-do-list-app-part-1) ``` - 帶有 Angular 5 的 ToDo 應用程式 ``` - [Introduction to Angular](http://www.discoversdk.com/blog/intro-to-angular-and-the-evolution-of-the-web) ``` ``` - [Part 1](http://www.discoversdk.com/blog/angular-5-to-do-list-app-part-1) ``` 難的 -- - [建構一個解釋器](http://www.craftinginterpreters.com/)(第 14 章是用 C 寫的) - [用 C 語言寫一個 Shell](https://brennan.io/2015/01/16/write-a-shell-in-c/) - [編寫 FUSE 文件系統](https://www.cs.nmsu.edu/~pfeiffer/fuse-tutorial/) - [建立您自己的文字編輯器](http://viewsourcecode.org/snaptoken/kilo/) - [建立自己的 Lisp](http://www.buildyourownlisp.com/) - [建構 CoreWiki](https://www.youtube.com/playlist?list=PLVMqA0_8O85yC78I4Xj7z48ES48IQBa7p)這是一個 Wiki 風格的內容管理系統,完全用 C# 使用 ASP.NET Core 和 Razor Pages 編寫。您可以[在這裡](https://github.com/csharpfritz/CoreWiki)找到原始程式碼。 - [建構 JIRA 與 Clojure 和 Atlassian Connect 的集成](https://hackernoon.com/building-a-jira-integration-with-clojure-atlassian-connect-506ebd112807) - [建構一個解釋器](http://www.craftinginterpreters.com/)(第 4-13 章是用 Java 寫的) - [使用 Mocha、React、Redux 和 Immutable 透過測試優先開發來建立全端電影投票應用程式](https://teropa.info/blog/2015/09/10/full-stack-redux-tutorial.html) - [使用 React 和 Node 建立 Twitter Stream](https://scotch.io/tutorials/build-a-real-time-twitter-stream-with-node-and-react-js) - 使用 Webtask.io 建立無伺服器 MERN Story 應用程式 ``` - [Part 1](https://scotch.io/tutorials/build-a-serverless-mern-story-app-with-webtask-io-zero-to-deploy-1) ``` ``` - [Part 2](https://scotch.io/tutorials/build-a-serverless-mern-story-app-with-webtask-io-zero-to-deploy-2) ``` - [使用 React + Parcel 建立 Chrome 擴充功能](https://medium.freecodecamp.org/building-chrome-extensions-in-react-parcel-79d0240dd58f) ``` [Testing React App With Pupepeteer and Jest](https://blog.bitsrc.io/testing-your-react-app-with-puppeteer-and-jest-c72b3dfcde59) ``` - [用 React 編寫生命遊戲](https://medium.freecodecamp.org/create-gameoflife-with-react-in-one-hour-8e686a410174) - [建立帶有情感分析的聊天應用程式](https://codeburst.io/build-a-chat-app-with-sentiment-analysis-using-next-js-c43ebf3ea643) - [建立全端 Web 應用程式設置](https://hackernoon.com/full-stack-web-application-using-react-node-js-express-and-webpack-97dbd5b9d708) - 建立隨機報價機 ``` - [Part 1](https://www.youtube.com/watch?v=3QngsWA9IEE) ``` ``` - [Part 2](https://www.youtube.com/watch?v=XnoTmO06OYo) ``` ``` - [Part 3](https://www.youtube.com/watch?v=us51Jne67_I) ``` ``` - [Part 4](https://www.youtube.com/watch?v=iZx7hqHb5MU) ``` ``` - [Part 5](https://www.youtube.com/watch?v=lpba9vBqXl0) ``` ``` - [Part 6](https://www.youtube.com/watch?v=Jvp8j6zrFHE) ``` ``` - [Part 7](https://www.youtube.com/watch?v=M_hFfrN8_PQ) ``` - 使用 Angular 6 建立美麗的現實世界應用程式: ``` - [Part I](https://medium.com/@hamedbaatour/build-a-real-world-beautiful-web-app-with-angular-6-a-to-z-ultimate-guide-2018-part-i-e121dd1d55e) ``` - [使用 BootStrap 4 和 Angular 6 建立響應式佈局](https://medium.com/@tomastrajan/how-to-build-responsive-layouts-with-bootstrap-4-and-angular-6-cfbb108d797b) - [使用 Django 和測試驅動開發建立待辦事項列表](http://www.obeythetestinggoat.com/) - [使用 Python 建立 RESTful 微服務](http://www.skybert.net/python/developing-a-restful-micro-service-in-python/) - [使用 Docker、Flask 和 React 的微服務](https://testdriven.io/) - [使用 Flask 建立簡單的 Web 應用程式](https://pythonspot.com/flask-web-app-with-python/) - [使用 Flask 建立 RESTful API – TDD 方式](https://scotch.io/tutorials/build-a-restful-api-with-flask-the-tdd-way) - [在 20 分鐘內建立 Django API](https://codeburst.io/create-a-django-api-in-under-20-minutes-2a082a60f6f3) 想法 == 簡單的 --- ### 99 瓶 - 建立一個程序,列印歌曲“牆上的 99 瓶啤酒”的每一行。 - 不要使用所有數字的列表,也不要手動輸入所有數字。請改用內建函數。 - 除了短語“取下一個”之外,您不得直接在歌詞中輸入任何數字/數字名稱。 - 請記住,當您還剩下 1 瓶時,「瓶子」一詞將變為單數。 ### 魔術8球 - 模擬神奇的 8 球。 - 允許使用者輸入他們的問題。 - 顯示正在進行的訊息(即“思考”)。 - 建立 20 個回應,並顯示隨機回應。 - 允許用戶提出另一個問題或退出。 - 獎金: ``` - Add a gui. ``` ``` - It must have a box for users to enter the question. ``` ``` - It must have at least 4 buttons: ``` ``` - ask ``` ``` - clear (the text box) ``` ``` - play again ``` ``` - quit (this must close the window) ``` ### 石頭剪刀布遊戲 - 建立一個石頭剪刀布遊戲。 - 讓玩家選擇石頭、剪刀或布。 - 讓計算機選擇它的移動方式。 - 比較選擇並決定誰獲勝。 - 列印結果。 - 子目標: ``` - Give the player the option to play again. ``` ``` - Keep a record of the score (e.g. Player: 3 / Computer: 6). ``` ### 倒數時鐘 - 建立一個程序,允許使用者選擇時間和日期,然後以給定的時間間隔(例如每秒)列印一條訊息,告訴使用者距離所選時間還有多長時間。 - 子目標: ``` - If the selected time has already passed, have the program tell the user to start over. ``` ``` - If your program asks for the year, month, day, hour, etc. separately, allow the user to be able to type in either the month name or its number. ``` ``` - TIP: Making use of built in modules such as time and datetime can change this project from a nightmare into a much simpler task. ``` 中等的 --- ### 番茄計時器 建立一個番茄計時器。 番茄計時器是一種時間管理方法。該技術使用計時器將工作分解為多個時間間隔,通常長度為 25 分鐘,中間間隔短暫的休息。這些間隔被命名為“pomodoros”,是意大利語單字“pomodoro”(番茄)的英文複數形式,以西里洛在大學時使用的番茄形狀的廚房計時器命名。 原始技巧有六個步驟: 決定要完成的任務。 設定番茄計時器(傳統上為 25 分鐘)。 完成任務。 當計時器響起時結束工作並在一張紙上畫上複選標記。 如果您的複選標記少於四個,請短暫休息(3-5 分鐘),然後轉到步驟 2。 四個番茄鐘後,休息較長時間(15-30 分鐘),將複選標記計數重設為零,然後轉到步驟 1。 要了解有關番茄計時器的更多訊息[,請單擊此處](https://en.wikipedia.org/wiki/Pomodoro_Technique) ### 谷歌案例 - 這是一個可以讓你玩英文句子的遊戲。 - 使用者將以任何格式輸入一個句子。(大寫或小寫或兩者的混合) - 程式必須將給定的句子轉換為Google大小寫。什麼是Google大小寫句子風格?\[know\_about\_it\_here:\](這是一種寫作風格,我們將所有小寫字母替換為大寫字母,留下所有單字的首字母)。 - 子目標: ``` - Program must then convert the given sentence in camel case.To know more about camel case ``` ``` [click_here](https://en.wikipedia.org/wiki/Camel_case) ``` ``` - Sentence can be entered with any number of spaces. ``` ### 擲骰子模擬器 - 允許使用者輸入骰子的面數以及應擲骰子的次數。 - 您的程式應該模擬擲骰子並追蹤每個數字出現的次數(這不必顯示)。 - 最後,列印出每個數字出現的次數。 - 子目標: ``` - Adjust your program so that if the user does not type in a number when they need to, the program will keep prompting them to type in a real number until they do so. ``` ``` - Put the program into a loop so that the user can continue to simulate dice rolls without having to restart the entire program. ``` ``` - In addition to printing out how many times each side appeared, also print out the percentage it appeared. If you can, round the percentage to 4 digits total OR two decimal places. ``` - 獎金: ``` - You are about to play a board game, but you realize you don't have any dice. Fortunately you have this program. ``` ``` - 1. Create a program that opens a new window and draws 2 six-sided dice ``` ``` - 2. Allow the user to quit, or roll again ``` ``` - Allow the user to select the number of dice to be drawn on screen(1-4) 2. Add up the total of the dice and display it ``` ### 計算並修復綠雞蛋和火腿 你們有些人可能還記得蘇博士的故事「綠雞蛋和火腿」。對於那些不記得或從未聽說過的人,[這](http://pastebin.com/XMY48CnN)是這個故事。然而,我給你的故事有一個問題——每次使用「我」這個詞時,它都是小寫的。 由於此問題,您的工作是執行以下操作: - 將我給您的故事複製到常規文字檔案中。 - 建立一個程式來通讀故事並在任何時候將字母 i 變為大寫。 (當它也用在 sam-I-am 的名字中時,請務必更改它。) - 讓你的程式建立一個新文件,並讓它正確地寫出故事。 - 印出有多少錯誤被修正。 - 完成後,您應該已經糾正了[這麼多](https://i.imgur.com/GRkj3yz.jpg)錯誤。 難的 -- ### 隨機維基百科文章 如果您曾造訪維基百科,您可能已經注意到螢幕左側有一個指向隨機文章的連結。雖然看到您被帶到哪篇文章可能很有趣,但有時看到文章的名稱會很好,這樣您就可以在聽起來很無聊時跳過它。幸運的是,維基百科有一個 API,允許我們這樣做[點擊這裡](https://en.wikipedia.org/w/api.php?action=query&list=random&rnnamespace=0&rnlimit=10&format=json)。 然而,有一個困境。由於維基百科擁有有關世界各地主題的文章,其中一些文章的標題中包含特殊字元。例如,關於西班牙畫家[埃拉斯托·科爾特斯·華雷斯 (Erasto Cortés Juárez)](https://en.wikipedia.org/wiki/Erasto_Cort%C3%A9s_Ju%C3%A1rez)的文章中就有 é 和 á。如果您查看這篇特定文章的[API](https://en.wikipedia.org/w/api.php?action=query&prop=info&pageids=39608394&inprop=url&format=json) ,您將看到標題是“Erasto Cort\\u00e9s Ju\\u00e1rez”,並且 \\u00e9 和 \\u00e1 正在替換前面提到的兩個字母。 (有關這是什麼的訊息,請首先查看文件中[本頁](https://docs.python.org/2/howto/unicode.html)的前半部分)。為了讓你的程式正常運作,你必須以某種方式處理這個問題。 - 建立一個程序,從官方維基百科 API 中提取標題,然後一一詢問用戶是否願意閱讀該文章。 - 例子: ``` - If the first title is Reddit, then the program should ask something along the lines of "Would you like to read about Reddit?" If the user says yes, then the program should open up the article for the user to read. ``` ``` - HINT: Click [here](https://en.wikipedia.org/wiki?curid=39608394) to see how the article's ID can be used to access the actual article. ``` - 子目標: ``` - As mentioned before, do something about the possibility of unicode appearing in the title. ``` ``` - Whether you want your program to simply filter out these articles or you want to actually turn the codes into readable characters, that's up to you. ``` ``` - Make the program pause once the user has selected an article to read, and allow him or her to continue browsing different article titles once finished reading. ``` ``` - Allow the user to simply press ENTER to be asked about a new article. ``` ### 天氣如何? 如果您想了解 API 的基礎知識,請查看 iamapizza 的[這篇](http://www.reddit.com/r/explainlikeimfive/comments/qowts/eli5_what_is_api/c3z9kok)文章。 - 建立一個程序,從 OpenWeatherMap.org 提取資料並列印有關當前天氣的訊息,例如您居住的地方的最高氣溫、最低氣溫和雨量。 - 子目標: ``` - Print out data for the next 5-7 days so you have a 5 day/week long forecast. ``` ``` - Print the data to another file that you can open up and view at, instead of viewing the information in the command line. ``` ``` - If you know html, write a file that you can print information to so that your project is more interesting. ``` - 尖端: ``` - APIs that are in Json are essentially lists and dictionaries. Remember that to reference something in a list, you must refer to it by what number element it is in the list, and to reference a key in a dictionary, you must refer to it by its name. ``` ``` - Don't like Celsius? Add &units=imperial to the end of the URL of the API to receive your data in Fahrenheit. ``` ### 來源 - https://github.com/tuvtran/project-based-learning - https://github.com/jorgegonzalez/beginner-projects - https://github.com/MunGell/awesome-for-beginners/blob/master/README.md - https://github.com/sarahbohr/AbsoluteBeginnerProjects --- 你怎麼認為?您喜歡透過特定專案進行學習還是不喜歡透過特定專案進行學習? --- 原文出處:https://dev.to/samborick/100-project-ideas-oda

我們編碼 2024!推動科技領域性別平等的變革 🔥💪🏽

每個人! **we\_coded**回來了,我們很高興與您一起慶祝整個三月。 --- ### **we\_coded**是什麼? **[we\_coded](https://dev.to/wecoded)**是我們的年度活動,致力於慶祝在科技業因性別原因而代表性不足和被邊緣化的 DEV 成員,特別是女性、跨性別和非二元性別個體。 **we\_coded**是六年前[\#SheCoded](https://dev.to/shecoded)開始的對話的延續,這是我們擴大聲音、分享經驗和培育更具包容性的技術未來的機會。歡迎盟友! --- ### 商店裡有什麼: > 日期:2024年3月1日至3月31日 **we\_coded**不僅是另一場活動,它還是一個共同參與有關科技領域性別平等的更廣泛討論的機會。我們可以共同透過分享您的想法、故事、想法和宣言來產生影響。 😉 今年,我們承諾: - 在 DEV 和我們的社交平台上展示您的故事、見解和想法 💫 - 用獨特的 we\_coded 徽章獎勵參與者 💖 我們希望這會帶來: - 重要的觀點、經驗和故事被放大🔊 - 志同道合的個人和組織之間建立新的聯繫。 🌱 - 社區的支持感🤗 --- ### 如何參與 無論是個人故事、建議或行動號召,您的貢獻都很重要。[從頭開始](https://dev.to/new)或使用[此範本](https://dev.to/new/wecoded)獲取靈感來發布您的貼文。 還沒準備好發布自己的貼文嗎?您可以透過對您閱讀的故事留下支持性評論和反應來放大聲音。即使是很小的行動也可以產生很大的影響。 讓我們推動改變——一次一個貼文、一則評論或一則反應! *注意:這是一項集體行動,旨在創造一個包容、無騷擾的環境!所有#wecoded 貼文都將由我們團隊中的人員進行審核。如果您想了解我們正在培育的社區,請造訪我們的[行為準則和社區準則](https://dev.to/code-of-conduct)。* {% 嵌入 https://dev.to/t/wecoded %} --- ### 讓我們有所作為! 我們可以共同創造一個更公平、更包容的科技產業。我們希望您能加入我們的**we\_coded 2024** ,並成為我們認為真正特別的事情的一部分。 你在嗎?使用**\#wecoded**分享您的興奮並傳播出去! --- 請繼續關注整個月的更新和公告。 --- 原文出處:https://dev.to/devteam/wecoded-2024-empowering-change-for-gender-equity-in-tech-30nj

Next.js 14 使用瀏覽器爬蟲,進行即時資料抓取的預訂應用程式

目錄 == - [介紹](#introduction) - [技術堆疊](#tech-stack) - [特徵](#features) - [設定 Next.js 應用程式](#step-1-setting-up-the-nextjs-application) - [安裝所需的套件](#step-2-installing-required-packages) - [設定 Redis 連接](#step-3-setting-up-redis-connection) - [配置 BullMQ 佇列](#step-4-configuring-bullmq-queue) - [Next.js 儀器設置](#step-5-nextjs-instrumentation-setup) - [設定 Bright Data 的抓取瀏覽器](#step-6-setting-up-bright-datas-scraping-browser) - [Bright Data 的抓取瀏覽器是什麼?](#what-is-bright-datas-scraping-browser) - [設定 Bright Data 抓取瀏覽器的步驟](#steps-to-set-up-bright-datas-scraping-browser) - [使用 Puppeteer 實作抓取邏輯](#implementing-the-scraping-logic-with-puppeteer) - [航班搜尋功能](#flight-search-feature) - [顯示航班搜尋結果](#displaying-flight-search-results) - [探索完整的指南和程式碼庫](#discover-the-complete-guide-and-codebase) - [在 YouTube 上觀看詳細說明](#watch-the-detailed-explanation-on-youtube) - [在 GitHub 上探索完整程式碼](#explore-the-full-code-on-github) - [結論](#conclusion) 介紹 == 在不斷發展的 Web 開發領域,有效收集、處理和顯示外部來源資料的能力變得越來越有價值。無論是市場研究、競爭分析或客戶洞察,網路抓取在釋放網路資料的巨大潛力方面都發揮著至關重要的作用。 這篇部落格文章介紹了建立強大的 Next.js 應用程式的綜合指南,該應用程式旨在從領先的旅行搜尋引擎之一 Kayak 抓取航班資料。透過利用 Next.js 的強大功能以及 BullMQ、Redis 和 Puppeteer 等現代技術。 技術堆疊 ==== - [Next.js](https://nextjs.org/docs) - [順風CSS](https://tailwindcss.com/docs) - [下一個介面](https://nextui.org/docs) - [健康)狀況](https://zustand.surge.sh/) - [條紋](https://stripe.com/docs) - [Bright Data 的抓取瀏覽器](https://brdta.com/kishansheth21) - [打字稿](https://www.typescriptlang.org/docs) - [雷迪斯](https://redis.io/documentation) - [BullMQ](https://docs.bullmq.io/) - [傀儡師](https://pptr.dev/) - [智威湯遜](https://jwt.io/introduction) - [阿克西奧斯](https://axios-http.com/docs/intro) - [PostgreSQL](https://www.postgresql.org/docs) - [棱鏡](https://www.prisma.io/docs) 特徵 == - 🚀 帶有 Tailwind CSS 的 Next.js 14 應用程式目錄 - 體驗由最新 Next.js 14 提供支援的時尚現代的 UI,並使用 Tailwind CSS 進行設計,以實現完美的外觀和感覺。 - 🔗 API 路由和伺服器操作 - 深入研究與 Next.js 14 的 API 路由和伺服器操作的無縫後端集成,確保高效的資料處理和伺服器端邏輯執行。 - 🕷 使用 Puppeteer Redis 和 BullMQ 進行抓取 - 利用 Puppeteer 的強大功能進行進階 Web 抓取,並使用 Redis 和 BullMQ 管理佇列和作業以實現強大的後端操作。 - 🔑 用於身份驗證和授權的 JWT 令牌 - 使用 JWT 令牌保護您的應用程式,為整個平台提供可靠的身份驗證和授權方法。 - 💳 支付網關 Stripe - 整合 Stripe 進行無縫支付處理,為預訂旅行、航班和飯店提供安全、輕鬆的交易。 - ✈️ 使用 Stripe 支付網關預訂旅行、航班和飯店 - 使用我們的 Stripe 支援的支付系統,讓您的旅遊預訂體驗變得輕鬆。 - 📊 從多個網站抓取即時資料 - 從多個來源抓取即時資料,保持領先,讓您的應用程式更新最新資訊。 - 💾 使用 Prisma 將抓取的資料儲存在 PostgreSQL 中 - 利用 PostgreSQL 和 Prisma 高效儲存和管理抓取的資料,確保可靠性和速度。 - 🔄 用於狀態管理的 Zustand - 透過 Zustand 簡化狀態邏輯並增強效能,在您的應用程式中享受流暢且可管理的狀態管理。 - 😈 該應用程式的最佳功能 - 使用 Bright Data 的抓取瀏覽器抓取不可抓取的資料。 ![抓取瀏覽器迷因](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e0ytki1wpsbvluk1qkpo.jpg) Bright Data的抓取瀏覽器為我們提供了自動驗證碼解決功能,可以幫助我們抓取不可抓取的資料。 第 1 步:設定 Next.js 應用程式 --------------------- 1. **建立 Next.js 應用程式**:首先建立一個新的 Next.js 應用程式(如果您還沒有)。您可以透過在終端機中執行以下命令來完成此操作: ``` npx create-next-app@latest booking-app ``` 2. **導航到您的應用程式目錄**:變更為您新建立的應用程式目錄: ``` cd booking-app ``` 步驟2:安裝所需的軟體包 ------------ 您需要安裝多個軟體包,包括 Redis、BullMQ 和 Puppeteer Core。執行以下命令來安裝它們: ``` npm install ioredis bullmq puppeteer-core ``` - `ioredis`是 Node.js 的強大 Redis 用戶端,支援與 Redis 進行通訊。 - `bullmq`以 Redis 作為後端來管理作業和訊息佇列。 - `puppeteer-core`可讓您控制外部瀏覽器以進行抓取。 步驟3:設定Redis連接 ------------- 在適當的目錄(例如`lib/` )中建立一個檔案(例如`redis.js` )來配置 Redis 連線: ``` // lib/redis.js import Redis from 'ioredis'; // Use REDIS_URL from environment or fallback to localhost const REDIS_URL = process.env.REDIS_URL || 'redis://localhost:6379'; const connection = new Redis(REDIS_URL); export { connection }; ``` 步驟4:配置BullMQ佇列 -------------- 透過在 Redis 配置所在的相同目錄中建立另一個檔案(例如, `queue.js` )來設定 BullMQ 佇列: ``` // lib/queue.js import { Queue } from 'bullmq'; import { connection } from './redis'; export const importQueue = new Queue('importQueue', { connection, defaultJobOptions: { attempts: 2, backoff: { type: 'exponential', delay: 5000, }, }, }); ``` 第 5 步:Next.js 儀器設置 ------------------ Next.js 允許偵測,可以在 Next.js 配置中啟用。您還需要建立一個用於作業處理的工作文件。 1.**在 Next.js 中啟用 Instrumentation** :將以下內容新增至`next.config.js`以啟用 Instrumentation: ``` // next.config.js module.exports = { experimental: { instrumentationHook: true, }, }; ``` 2.**建立用於作業處理的 Worker** :在您的應用程式中,建立一個檔案 ( `instrumentation.js` ) 來處理作業處理。該工作人員將使用 Puppeteer 來執行抓取任務: ``` // instrumentation.js export const register = async () => { if (process.env.NEXT_RUNTIME === 'nodejs') { const { Worker } = await import('bullmq'); const puppeteer = await import('puppeteer-core'); const { connection } = await import('./lib/redis'); const { importQueue } = await import('./lib/queue'); new Worker('importQueue', async (job) => { // Job processing logic with Puppeteer goes here }, { connection, concurrency: 10, removeOnComplete: { count: 1000 }, removeOnFail: { count: 5000 }, }); } }; ``` 第 6 步:設定 Bright Data 的抓取瀏覽器 --------------------------- 在設定 Bright 資料抓取瀏覽器之前,我們先來談談什麼是抓取瀏覽器。 ### Bright Data 的抓取瀏覽器是什麼? Bright Data 的抓取瀏覽器是一款用於自動網頁抓取的尖端工具,旨在與 Puppeteer、Playwright 和 Selenium 無縫整合。它提供了一套網站解鎖功能,包括代理輪換、驗證碼解決等,以提高抓取效率。它非常適合需要互動的複雜網頁抓取,透過在 Bright Data 基礎架構上託管無限的瀏覽器會話來實現可擴展性。如欲了解更多詳情,請造訪[光明資料](https://brdta.com/kishansheth21)。 ![明亮的資料抓取瀏覽器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c70ochb1lgdrusgicwz4.png) <a id="steps-to-set-up-bright-datas-scraping-browser"></a> #### 第 1 步:導覽至 Bright Data 網站 首先造訪[Brightdata.com](https://brdta.com/kishansheth21) 。這是您存取 Bright Data 提供的豐富網頁抓取資源和工具的入口。 ![光明資料首頁](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/afgkpgytcytoqfuq0h8w.png) #### 第 2 步:建立帳戶 造訪 Bright Data 網站後,註冊並建立一個新帳戶。系統將提示您輸入基本資訊以啟動並執行您的帳戶。 ![登入/註冊 Bright Data](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ffha75szs9tubh8kra9j.png) #### 第 3 步:選擇您的產品 在產品選擇頁面上,尋找代理商和抓取基礎設施產品。本產品專為滿足您的網路抓取需求而設計,提供強大的資料擷取工具和功能。 ![光明資料產品](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b058azlmjv30po6289fh.png) #### 第 4 步:新增代理 在「代理程式和抓取基礎設施」頁面中,您會找到一個「新增按鈕」。點擊此按鈕開始將新的抓取瀏覽器新增到您的工具包的過程。 ![新代理](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2jscxsyt9yess1nvzi4z.png) #### 第五步:選擇抓取瀏覽器 將出現一個下拉列表,您應該從中選擇抓取瀏覽器選項。這告訴 Bright Data 您打算設定一個新的抓取瀏覽器環境。 ![選擇抓取瀏覽器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i483ipx7spwne65c6tep.png) #### 第 6 步:為您的抓取瀏覽器命名 為您的新抓取瀏覽器指定一個唯一的名稱。這有助於稍後辨識和管理它,特別是如果您計劃對不同的抓取專案使用多個瀏覽器。 ![抓取瀏覽器名稱](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n0qnitec7s7gki7t3826.png) #### 步驟7:新增瀏覽器 命名您的瀏覽器後,按一下「新增」按鈕。此操作完成了新的抓取瀏覽器的建立。 ![新增抓取瀏覽器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ao6n1edyyx2no621nh01.png) #### 第 8 步:查看您的抓取瀏覽器詳細訊息 新增抓取瀏覽器後,您將被導向到一個頁面,您可以在其中查看新建立的抓取瀏覽器的所有詳細資訊。這些資訊對於整合和使用至關重要。 ![抓取瀏覽器詳細訊息](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ev33mbgznevn6h9p60g6.png) #### 第 9 步:存取程式碼和整合範例 尋找“查看程式碼和整合範例”按鈕。點擊此按鈕將為您提供如何跨多種程式語言和程式庫整合和使用抓取瀏覽器的全面視圖。對於希望自訂抓取設定的開發人員來說,此資源非常寶貴。 ![程式碼和整合範例按鈕](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/30araqzko585yzmhrumd.png) #### 第 10 步:整合您的抓取瀏覽器 最後,複製 SRS\_WS\_ENDPOINT 變數。這是一條關鍵訊息,您需要將其整合到原始程式碼中,以便您的應用程式能夠與您剛剛設定的抓取瀏覽器進行通訊。 ![抓取瀏覽器端點](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kqhpglz1lngobguk2nu4.png) 透過遵循這些詳細步驟,您已在 Bright Data 平台中成功建立了一個抓取瀏覽器,準備好處理您的網頁抓取任務。請記住,Bright Data 提供廣泛的文件和支持,幫助您最大限度地提高抓取專案的效率和效果。無論您是在收集市場情報、進行研究還是監控競爭格局,新設定的抓取瀏覽器都是資料收集庫中的強大工具。 ### 第 7 步:使用 Puppeteer 實作抓取邏輯 從我們上次設定用於抓取航班資料的 Next.js 應用程式的地方開始,下一個關鍵步驟是實現實際的抓取邏輯。此過程涉及利用 Puppeteer 連接到瀏覽器實例、導航到目標 URL(在我們的範例中為 Kayak)並抓取必要的飛行資料。提供的程式碼片段概述了實現此目標的複雜方法,與我們先前建立的 BullMQ 工作設定無縫整合。讓我們分解這個抓取邏輯的元件,並了解它如何適合我們的應用程式。 #### 建立與瀏覽器的連接 我們抓取過程的第一步是透過 Puppeteer 建立與瀏覽器的連線。這是透過利用`puppeteer.connect`方法來完成的,該方法使用 WebSocket 端點 ( `SBR_WS_ENDPOINT` ) 連接到現有的瀏覽器實例。此環境變數應設定為您正在使用的抓取瀏覽器服務的 WebSocket URL,例如 Bright Data: ``` const browser = await puppeteer.connect({ browserWSEndpoint: SBR_WS_ENDPOINT, }); ``` #### 開啟新頁面並導航到目標 URL 連線後,我們在瀏覽器中建立一個新頁面並導航到作業資料中指定的目標 URL。此 URL 是我們打算從中抓取航班資料的特定 Kayak 搜尋結果頁面: ``` const page = await browser.newPage(); await page.goto(job.data.url); ``` #### 抓取航班資料 我們邏輯的核心在於從頁面中抓取航班資料。我們透過使用`page.evaluate`來實現這一點,這是一種 Puppeteer 方法,允許我們在瀏覽器上下文中執行腳本。在此腳本中,我們等待必要的元素加載,然後繼續收集航班資訊: - **Flight Selector** :我們以`.nrc6-wrapper`類別為目標元素,其中包含航班詳細資訊。 - **資料擷取**:對於每個航班元素,我們提取詳細訊息,例如航空公司徽標、出發和到達時間、航班持續時間、航空公司名稱和價格。出發和到達時間經過清理,以刪除最後不必要的數值,確保我們準確地捕捉時間。 - **價格處理**:價格在刪除所有非數字字元後提取為整數,確保其可用於數值運算或比較。 擷取的資料被建構成飛行物件陣列,每個物件都包含上述詳細資訊: ``` const scrappedFlights = await page.evaluate(async () => { // Data extraction logic const flights = []; // Process each flight element // ... return flights; }); ``` #### 錯誤處理和清理 我們的抓取邏輯被包裝在一個 try-catch 區塊中,以在抓取過程中優雅地處理任何潛在的錯誤。無論結果如何,我們都會確保瀏覽器在finally區塊中正確關閉,從而保持資源效率並防止潛在的記憶體洩漏: ``` try { // Scraping logic } catch (error) { console.log({ error }); } finally { await browser.close(); console.log("Browser closed successfully."); } ``` #### 整個程式碼 ``` const SBR_WS_ENDPOINT = process.env.SBR_WS_ENDPOINT; export const register = async () => { if (process.env.NEXT_RUNTIME === "nodejs") { const { Worker } = await import("bullmq"); const puppeteer = await import("puppeteer"); const { connection } = await import("./lib/redis"); const { importQueue } = await import("./lib/queue"); new Worker( "importQueue", async (job) => { const browser = await puppeteer.connect({ browserWSEndpoint: SBR_WS_ENDPOINT, }); try { const page = await browser.newPage(); console.log("in flight scraping"); console.log("Connected! Navigating to " + job.data.url); await page.goto(job.data.url); console.log("Navigated! Scraping page content..."); const scrappedFlights = await page.evaluate(async () => { await new Promise((resolve) => setTimeout(resolve, 5000)); const flights = []; const flightSelectors = document.querySelectorAll(".nrc6-wrapper"); flightSelectors.forEach((flightElement) => { const airlineLogo = flightElement.querySelector("img")?.src || ""; const [rawDepartureTime, rawArrivalTime] = ( flightElement.querySelector(".vmXl")?.innerText || "" ).split(" – "); // Function to extract time and remove numeric values at the end const extractTime = (rawTime: string): string => { const timeWithoutNumbers = rawTime .replace(/[0-9+\s]+$/, "") .trim(); return timeWithoutNumbers; }; const departureTime = extractTime(rawDepartureTime); const arrivalTime = extractTime(rawArrivalTime); const flightDuration = ( flightElement.querySelector(".xdW8")?.children[0]?.innerText || "" ).trim(); const airlineName = ( flightElement.querySelector(".VY2U")?.children[1]?.innerText || "" ).trim(); // Extract price const price = parseInt( ( flightElement.querySelector(".f8F1-price-text")?.innerText || "" ) .replace(/[^\d]/g, "") .trim(), 10 ); flights.push({ airlineLogo, departureTime, arrivalTime, flightDuration, airlineName, price, }); }); return flights; }); } catch (error) { console.log({ error }); } finally { await browser.close(); console.log("Browser closed successfully."); } }, { connection, concurrency: 10, removeOnComplete: { count: 1000 }, removeOnFail: { count: 5000 }, } ); } }; ``` ### 步驟8:航班搜尋功能 基於我們的航班資料抓取功能,讓我們將全面的航班搜尋功能整合到我們的 Next.js 應用程式中。此功能將為使用者提供一個動態介面,透過指定出發地、目的地和日期來搜尋航班。利用強大的 Next.js 框架以及現代 UI 庫和狀態管理,我們建立了引人入勝且響應迅速的航班搜尋體驗。 #### 航班搜尋功能的關鍵組成部分 1. **動態城市選擇**:此功能包括來源和目的地輸入的自動完成功能,由預先定義的城市機場程式碼清單提供支援。當使用者輸入時,應用程式會過濾並顯示匹配的城市,透過更輕鬆地尋找和選擇機場來增強用戶體驗。 2. **日期選擇**:使用者可以透過日期輸入選擇預期的航班日期,為規劃旅行提供彈性。 3. **抓取狀態監控**:啟動抓取作業後,應用程式透過定期 API 呼叫來監控作業的狀態。這種非同步檢查允許應用程式使用抓取過程的狀態更新 UI,確保使用者了解進度和結果。 #### 航班搜尋元件的完整程式碼 ``` "use client"; import { useAppStore } from "@/store"; import { USER_API_ROUTES } from "@/utils/api-routes"; import { cityAirportCode } from "@/utils/city-airport-codes"; import { Button, Input, Listbox, ListboxItem } from "@nextui-org/react"; import axios from "axios"; import Image from "next/image"; import { useRouter } from "next/navigation"; import React, { useEffect, useRef, useState } from "react"; import { FaCalendarAlt, FaSearch } from "react-icons/fa"; const SearchFlights = () => { const router = useRouter(); const { setScraping, setScrapingType, setScrappedFlights } = useAppStore(); const [loadingJobId, setLoadingJobId] = useState<number | undefined>(undefined); const [source, setSource] = useState(""); const [sourceOptions, setSourceOptions] = useState< { city: string; code: string; }[] >([]); const [destination, setDestination] = useState(""); const [destinationOptions, setDestinationOptions] = useState< { city: string; code: string; }[] >([]); const [flightDate, setFlightDate] = useState(() => { const today = new Date(); return today.toISOString().split("T")[0]; }); const handleSourceChange = (query: string) => { const matchingCities = Object.entries(cityAirportCode) .filter(([, city]) => city.toLowerCase().includes(query.toLowerCase())) .map(([code, city]) => ({ code, city })) .splice(0, 5); setSourceOptions(matchingCities); }; const destinationChange = (query: string) => { const matchingCities = Object.entries(cityAirportCode) .filter(([, city]) => city.toLowerCase().includes(query.toLowerCase())) .map(([code, city]) => ({ code, city })) .splice(0, 5); setDestinationOptions(matchingCities); }; const startScraping = async () => { if (source && destination && flightDate) { const data = await axios.get(`${USER_API_ROUTES.FLIGHT_SCRAPE}?source=${source}&destination=${destination}&date=${flightDate}`); if (data.data.id) { setLoadingJobId(data.data.id); setScraping(true); setScrapingType("flight"); } } }; useEffect(() => { if (loadingJobId) { const checkIfJobCompleted = async () => { try { const response = await axios.get(`${USER_API_ROUTES.FLIGHT_SCRAPE_STATUS}?jobId=${loadingJobId}`); if (response.data.status) { set ScrappedFlights(response.data.flights); clearInterval(jobIntervalRef.current); setScraping(false); setScrapingType(undefined); router.push(`/flights?data=${flightDate}`); } } catch (error) { console.log(error); } }; jobIntervalRef.current = setInterval(checkIfJobCompleted, 3000); } return () => clearInterval(jobIntervalRef.current); }, [loadingJobId]); return ( <div className="h-[90vh] flex items-center justify-center"> <div className="absolute left-0 top-0 h-[100vh] w-[100vw] max-w-[100vw] overflow-hidden overflow-x-hidden"> <Image src="/flight-search.png" fill alt="Search" /> </div> <div className="absolute h-[50vh] w-[60vw] flex flex-col gap-5"> {/* UI and functionality for flight search */} </div> </div> ); }; export default SearchFlights; ``` ### 步驟9:航班搜尋頁面UI ![航班搜尋頁面](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/54bkhpea27fkzg4vlur1.png) ### 顯示航班搜尋結果 成功抓取飛行資料後,下一個關鍵步驟是以使用者友善的方式將這些結果呈現給使用者。 Next.js 應用程式中的 Flights 元件就是為此目的而設計的。 ``` "use client"; import { useAppStore } from "@/store"; import { USER_API_ROUTES } from "@/utils/api-routes"; import { Button } from "@nextui-org/react"; import axios from "axios"; import Image from "next/image"; import { useRouter, useSearchParams } from "next/navigation"; import React from "react"; import { FaChevronLeft } from "react-icons/fa"; import { MdOutlineFlight } from "react-icons/md"; const Flights = () => { const router = useRouter(); const searchParams = useSearchParams(); const date = searchParams.get("date"); const { scrappedFlights, userInfo } = useAppStore(); const getRandomNumber = () => Math.floor(Math.random() * 41); const bookFLight = async (flightId: number) => {}; return ( <div className="m-10 px-[20vw] min-h-[80vh]"> <Button className="my-5" variant="shadow" color="primary" size="lg" onClick={() => router.push("/search-flights")} > <FaChevronLeft /> Go Back </Button> <div className="flex-col flex gap-5"> {scrappedFlights.length === 0 && ( <div className="flex items-center justify-center py-5 px-10 mt-10 rounded-lg text-red-500 bg-red-100 font-medium"> No Flights found. </div> )} {scrappedFlights.map((flight: any) => { const seatsLeft = getRandomNumber(); return ( <div key={flight.id} className="grid grid-cols-12 border bg-gray-200 rounded-xl font-medium drop-shadow-md" > <div className="col-span-9 bg-white rounded-l-xl p-10 flex flex-col gap-5"> <div className="grid grid-cols-4 gap-4"> <div className="flex flex-col gap-3 font-medium"> <div> <div className="relative w-20 h-16"> <Image src={flight.logo} alt="airline name" fill /> </div> </div> <div>{flight.name}</div> </div> <div className="col-span-3 flex justify-between"> <div className="flex flex-col gap-2"> <div className="text-blue-600">From</div> <div> <span className="text-3xl"> <strong>{flight.departureTime}</strong> </span> </div> <div>{flight.from}</div> </div> <div className="flex flex-col items-center justify-center gap-2"> <div className="bg-violet-100 w-max p-3 text-4xl text-blue-600 rounded-full"> <MdOutlineFlight /> </div> <div> <span className="text-lg"> <strong>Non-stop</strong> </span> </div> <div>{flight.duration}</div> </div> <div className="flex flex-col gap-2"> <div className="text-blue-600">To</div> <div> <span className="text-3xl"> <strong>{flight.arrivalTime}</strong> </span> </div> <div>{flight.to}</div> </div> </div> </div> <div className="flex justify-center gap-10 bg-violet-100 p-3 rounded-lg"> <div className="flex"> <span>Airplane  </span> <span className="text-blue-600 font-semibold"> Boeing 787 </span> </div> <div className="flex"> <span>Travel Class:  </span> <span className="text-blue-600 font-semibold">Economy</span> </div> </div> <div className="flex justify-between font-medium"> <div> Refundable <span className="text-blue-600"> $5 ecash</span> </div> <div className={`${ seatsLeft > 20 ? "text-green-500" : "text-red-500" }`} > Only {seatsLeft} Seats Left </div> <div className="cursor-pointer">Flight Details</div> </div> </div> <div className="col-span-3 bg-violet-100 rounded-r-xl h-full flex flex-col items-center justify-center gap-5"> <div> <div> <span className="line-through font-light"> ${flight.price + 140} </span> </div> <div className="flex items-center gap-2"> <span className="text-5xl font-bold">${flight.price}</span> <span className="text-blue-600">20% OFF</span> </div> </div> <Button variant="ghost" radius="full" size="lg" color="primary" onClick={() => { if (userInfo) bookFLight(flight.id); }} > {userInfo ? "Book Now" : "Login to Book"} </Button> </div> </div> ); })} </div> </div> ); }; export default Flights; ``` #### 航班搜尋結果 ![航班搜尋結果](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cxufusoyrf6hgtrrcmsw.png) ### 探索完整的指南和程式碼庫 上面共享的部分和程式碼片段僅代表使用 Next.js 建立強大的航班資料抓取和搜尋應用程式所需的完整功能和程式碼的一小部分。為了掌握這個專案的全部內容,包括高級功能、優化和最佳實踐,我邀請您更深入地研究我的線上綜合資源。 #### 在 YouTube 上觀看詳細說明 有關引導您完成此應用程式的開發過程、編碼細微差別和功能的逐步影片指南,請觀看我的 YouTube 影片。本教程旨在讓您更深入地了解這些概念,讓您按照自己的步調進行操作並獲得對 Next.js 應用程式開發的寶貴見解。 https://www.youtube.com/watch?v=ZWVhk0fxHM0 #### 在 GitHub 上探索完整程式碼 如果您渴望探索完整的程式碼,請造訪我的 GitHub 儲存庫。在那裡,您將找到完整的程式碼庫,包括讓該應用程式在您自己的電腦上執行所需的所有元件、實用程式和設定說明。 https://github.com/koolkishan/nextjs-travel-planner ### 結論 使用 Next.js 建立飛行資料抓取和搜尋工具等綜合應用程式展示了現代 Web 開發工具和框架的強大功能和多功能性。無論您是希望提高技能的經驗豐富的開發人員,還是渴望深入 Web 開發的初學者,這些資源都是為您的旅程量身定制的。在 YouTube 上觀看詳細教程,在 GitHub 上探索完整程式碼,並加入對話以增強您的開發專業知識並為充滿活力的開發者社群做出貢獻。 --- 原文出處:https://dev.to/kishansheth/nextjs-14-booking-app-with-live-data-scraping-using-scraping-browser-610

為初學者到專家提供的 101 個 Bash 指令和提示

> **2019 年 9 月 25 日更新:**感謝[ラナ・kuaru](https://twitter.com/rana_kualu)的辛勤工作,本文現已提供日文版。請點擊下面的連結查看他們的工作。如果您知道本文被翻譯成其他語言,請告訴我,我會將其發佈在這裡。 [🇯🇵 閱讀日語](https://qiita.com/rana_kualu/items/7b62898d373901466f5c) > **2019 年 7 月 8 日更新:**我最近發現大約兩年前發佈在法語留言板上的[這篇非常相似的文章](https://bookmarks.ecyseo.net/?EAWvDw)。如果您有興趣學習一些 shell 命令——並且您*會說 français* ,那麼它是對我下面的文章的一個很好的補充。 直到大約一年前,我幾乎只在 macOS 和 Ubuntu 作業系統中工作。在這兩個作業系統上, `bash`是我的預設 shell。在過去的六、七年裡,我對`bash`工作原理有了大致的了解,並想為那些剛入門的人概述一些更常見/有用的命令。如果您認為您了解有關`bash`所有訊息,請無論如何看看下面的內容 - 我已經提供了一些提示和您可能忘記的標誌的提醒,這可以讓您的工作更輕鬆一些。 下面的命令或多或少以敘述風格排列,因此如果您剛開始使用`bash` ,您可以從頭到尾完成操作。事情到最後通常會變得不那麼常見並且變得更加困難。 <a name="toc"></a> 目錄 -- - [基礎](#the-basics) ``` - [First Commands, Navigating the Filesystem](#first-commands) ``` ``` - [`pwd / ls / cd`](#pwd-ls-cd) ``` ``` - [`; / && / &`](#semicolon-andand-and) ``` ``` - [Getting Help](#getting-help) ``` ``` - [`-h`](#minus-h) ``` ``` - [`man`](#man) ``` ``` - [Viewing and Editing Files](#viewing-and-editing-files) ``` ``` - [`head / tail / cat / less`](#head-tail-cat-less) ``` ``` - [`nano / nedit`](#nano-nedit) ``` ``` - [Creating and Deleting Files and Directories](#creating-and-deleting-files) ``` ``` - [`touch`](#touch) ``` ``` - [`mkdir / rm / rmdir`](#mkdir-rm-rmdir) ``` ``` - [Moving and Copying Files, Making Links, Command History](#moving-and-copying-files) ``` ``` - [`mv / cp / ln`](#mv-cp-ln) ``` ``` - [Command History](#command-history) ``` ``` - [Directory Trees, Disk Usage, and Processes](#directory-trees-disk-usage-processes) ``` ``` - [`mkdir –p / tree`](#mkdir--p-tree) ``` ``` - [`df / du / ps`](#df-du-ps) ``` ``` - [Miscellaneous](#basic-misc) ``` ``` - [`passwd / logout / exit`](#passwd-logout-exit) ``` ``` - [`clear / *`](#clear-glob) ``` - [中間的](#intermediate) ``` - [Disk, Memory, and Processor Usage](#disk-memory-processor) ``` ``` - [`ncdu`](#ncdu) ``` ``` - [`top / htop`](#top-htop) ``` ``` - [REPLs and Software Versions](#REPLs-software-versions) ``` ``` - [REPLs](#REPLs) ``` ``` - [`-version / --version / -v`](#version) ``` ``` - [Environment Variables and Aliases](#env-vars-aliases) ``` ``` - [Environment Variables](#env-vars) ``` ``` - [Aliases](#aliases) ``` ``` - [Basic `bash` Scripting](#basic-bash-scripting) ``` ``` - [`bash` Scripts](#bash-scripts) ``` ``` - [Custom Prompt and `ls`](#custom-prompt-ls) ``` ``` - [Config Files](#config-files) ``` ``` - [Config Files / `.bashrc`](#config-bashrc) ``` ``` - [Types of Shells](#types-of-shells) ``` ``` - [Finding Things](#finding-things) ``` ``` - [`whereis / which / whatis`](#whereis-which-whatis) ``` ``` - [`locate / find`](#locate-find) ``` ``` - [Downloading Things](#downloading-things) ``` ``` - [`ping / wget / curl`](#ping-wget-curl) ``` ``` - [`apt / gunzip / tar / gzip`](#apt-gunzip-tar-gzip) ``` ``` - [Redirecting Input and Output](#redirecting-io) ``` ``` - [`| / > / < / echo / printf`](#pipe-gt-lt-echo-printf) ``` ``` - [`0 / 1 / 2 / tee`](#std-tee) ``` - [先進的](#advanced) ``` - [Superuser](#superuser) ``` ``` - [`sudo / su`](#sudo-su) ``` ``` - [`!!`](#click-click) ``` ``` - [File Permissions](#file-permissions) ``` ``` - [File Permissions](#file-permissions-sub) ``` ``` - [`chmod / chown`](#chmod-chown) ``` ``` - [User and Group Management](#users-groups) ``` ``` - [Users](#users) ``` ``` - [Groups](#groups) ``` ``` - [Text Processing](#text-processing) ``` ``` - [`uniq / sort / diff / cmp`](#uniq-sort-diff-cmp) ``` ``` - [`cut / sed`](#cut-sed) ``` ``` - [Pattern Matching](#pattern-matching) ``` ``` - [`grep`](#grep) ``` ``` - [`awk`](#awk) ``` ``` - [Copying Files Over `ssh`](#ssh) ``` ``` - [`ssh / scp`](#ssh-scp) ``` ``` - [`rsync`](#rsync) ``` ``` - [Long-Running Processes](#long-running-processes) ``` ``` - [`yes / nohup / ps / kill`](#yes-nohup-ps-kill) ``` ``` - [`cron / crontab / >>`](#cron) ``` ``` - [Miscellaneous](#advanced-misc) ``` ``` - [`pushd / popd`](#pushd-popd) ``` ``` - [`xdg-open`](#xdg-open) ``` ``` - [`xargs`](#xargs) ``` - [獎勵:有趣但大多無用的東西](#bonus) ``` - [`w / write / wall / lynx`](#w-write-wall-lynx) ``` ``` - [`nautilus / date / cal / bc`](#nautilus-date-cal-bc) ``` --- <a name="the-basics"></a> 基礎 == <a name="first-commands"></a> 第一個指令,瀏覽檔案系統 ------------ 現代檔案系統具有目錄(資料夾)樹,其中目錄要么是*根目錄*(沒有父目錄),要么是*子目錄*(包含在單一其他目錄中,我們稱之為“父目錄”)。向後遍歷檔案樹(從子目錄到父目錄)將始終到達根目錄。有些檔案系統有多個根目錄(如 Windows 的磁碟機: `C:\` 、 `A:\`等),但 Unix 和類別 Unix 系統只有一個名為`\`的根目錄。 <a name="pwd-ls-cd"></a> ### `pwd / ls / cd` [\[ 返回目錄 \]](#toc) 在檔案系統中工作時,使用者始終*在*某個目錄中工作,我們稱之為當前目錄或*工作目錄*。使用`pwd`列印使用者的工作目錄: ``` [ andrew@pc01 ~ ]$ pwd /home/andrew ``` 使用`ls`列出該目錄的內容(檔案和/或子目錄等): ``` [ andrew@pc01 ~ ]$ ls Git TEST jdoc test test.file ``` > **獎金:** > > 使用`ls -a`顯示隱藏(“點”)文件 > > 使用`ls -l`顯示文件詳細訊息 > > 組合多個標誌,如`ls -l -a` > > 有時您可以連結諸如`ls -la`之類的標誌,而不是`ls -l -a` 使用`cd`更改到不同的目錄(更改目錄): ``` [ andrew@pc01 ~ ]$ cd TEST/ [ andrew@pc01 TEST ]$ pwd /home/andrew/TEST [ andrew@pc01 TEST ]$ cd A [ andrew@pc01 A ]$ pwd /home/andrew/TEST/A ``` `cd ..`是「 `cd`到父目錄」的簡寫: ``` [ andrew@pc01 A ]$ cd .. [ andrew@pc01 TEST ]$ pwd /home/andrew/TEST ``` `cd ~`或只是`cd`是「 `cd`到我的主目錄」的簡寫(通常`/home/username`或類似的東西): ``` [ andrew@pc01 TEST ]$ cd [ andrew@pc01 ~ ]$ pwd /home/andrew ``` > **獎金:** > > `cd ~user`表示「 `cd`到`user`的主目錄 > > 您可以使用`cd ../..`等跳轉多個目錄等級。 > > 使用`cd -`返回到最近的目錄 > > `.`是「此目錄」的簡寫,因此`cd .`不會做太多事情 <a name="semicolon-andand-and"></a> ### `; / && / &` [\[ 返回目錄 \]](#toc) 我們在命令列中輸入的內容稱為*命令*,它們總是執行儲存在電腦上某處的一些機器碼。有時這個機器碼是一個內建的Linux命令,有時它是一個應用程式,有時它是你自己寫的一些程式碼。有時,我們會想依序執行一個指令。為此,我們可以使用`;` (分號): ``` [ andrew@pc01 ~ ]$ ls; pwd Git TEST jdoc test test.file /home/andrew ``` 上面的分號表示我首先 ( `ls` ) 列出工作目錄的內容,然後 ( `pwd` ) 列印其位置。連結命令的另一個有用工具是`&&` 。使用`&&`時,如果左側命令失敗,則右側命令將不會執行。 `;`和`&&`都可以在同一行中多次使用: ``` # whoops! I made a typo here! [ andrew@pc01 ~ ]$ cd /Giit/Parser && pwd && ls && cd -bash: cd: /Giit/Parser: No such file or directory # the first command passes now, so the following commands are run [ andrew@pc01 ~ ]$ cd Git/Parser/ && pwd && ls && cd /home/andrew/Git/Parser README.md doc.sh pom.xml resource run.sh shell.sh source src target ``` ....但是與`;` ,即使第一個命令失敗,第二個命令也會執行: ``` # pwd and ls still run, even though the cd command failed [ andrew@pc01 ~ ]$ cd /Giit/Parser ; pwd ; ls -bash: cd: /Giit/Parser: No such file or directory /home/andrew Git TEST jdoc test test.file ``` `&`看起來與`&&`類似,但實際上實現了完全不同的功能。通常,當您執行長時間執行的命令時,命令列將等待該命令完成,然後才允許您輸入另一個命令。在命令後面加上`&`可以防止這種情況發生,並允許您在舊命令仍在執行時執行新命令: ``` [ andrew@pc01 ~ ]$ cd Git/Parser && mvn package & cd [1] 9263 ``` > **額外的好處:**當我們在命令後使用`&`來「隱藏」它時,我們說該作業(或「進程」;這些術語或多或少可以互換)是「後台的」。若要查看目前正在執行的背景作業,請使用`jobs`指令: > ````bash \[ andrew@pc01 ~ \]$ 職位 \[1\]+ 執行 cd Git/Parser/ && mvn package & ``` <a name="getting-help"></a> ## Getting Help <a name="minus-h"></a> ### `-h` [[ Back to Table of Contents ]](#toc) Type `-h` or `--help` after almost any command to bring up a help menu for that command: ``` \[ andrew@pc01 ~ \]$ du --help 用法:你\[選項\]...\[檔案\]... 或: du \[選項\]... --files0-from=F 對目錄遞歸地總結文件集的磁碟使用情況。 長期權的強制性參數對於短期權也是強制性的。 -0, --null 以 NUL 結束每個輸出行,而不是換行符 -a, --all 計算所有檔案的寫入計數,而不僅僅是目錄 ``` --apparent-size print apparent sizes, rather than disk usage; although ``` ``` the apparent size is usually smaller, it may be ``` ``` larger due to holes in ('sparse') files, internal ``` ``` fragmentation, indirect blocks, and the like ``` -B, --block-size=SIZE 在列印前按 SIZE 縮放大小;例如, ``` '-BM' prints sizes in units of 1,048,576 bytes; ``` ``` see SIZE format below ``` … ``` <a name="man"></a> ### `man` [[ Back to Table of Contents ]](#toc) Type `man` before almost any command to bring up a manual for that command (quit `man` with `q`): ``` LS(1) 使用者指令 LS(1) 姓名 ``` ls - list directory contents ``` 概要 ``` ls [OPTION]... [FILE]... ``` 描述 ``` List information about the FILEs (the current directory by default). ``` ``` Sort entries alphabetically if none of -cftuvSUX nor --sort is speci- ``` ``` fied. ``` ``` Mandatory arguments to long options are mandatory for short options ``` ``` too. ``` … ``` <a name="viewing-and-editing-files"></a> ## Viewing and Editing Files <a name="head-tail-cat-less"></a> ### `head / tail / cat / less` [[ Back to Table of Contents ]](#toc) `head` outputs the first few lines of a file. The `-n` flag specifies the number of lines to show (the default is 10): ``` 列印前三行 ===== \[ andrew@pc01 ~ \]$ 頭 -n 3 c 這 文件 有 ``` `tail` outputs the last few lines of a file. You can get the last `n` lines (like above), or you can get the end of the file beginning from the `N`-th line with `tail -n +N`: ``` 從第 4 行開始列印文件末尾 ============== \[ andrew@pc01 ~ \]$ tail -n +4 c 確切地 六 線 ``` `cat` concatenates a list of files and sends them to the standard output stream (usually the terminal). `cat` can be used with just a single file, or multiple files, and is often used to quickly view them. (**Be warned**: if you use `cat` in this way, you may be accused of a [_Useless Use of Cat_ (UUOC)](http://bit.ly/2SPHE4V), but it's not that big of a deal, so don't worry too much about it.) ``` \[ andrew@pc01 ~ \]$ 貓 a 歸檔一個 \[ andrew@pc01 ~ \]$ 貓 ab 歸檔一個 文件b ``` `less` is another tool for quickly viewing a file -- it opens up a `vim`-like read-only window. (Yes, there is a command called `more`, but `less` -- unintuitively -- offers a superset of the functionality of `more` and is recommended over it.) Learn more (or less?) about [less](http://man7.org/linux/man-pages/man1/less.1.html) and [more](http://man7.org/linux/man-pages/man1/more.1.html) at their `man` pages. <a name="nano-nedit"></a> ### `nano / nedit` [[ Back to Table of Contents ]](#toc) `nano` is a minimalistic command-line text editor. It's a great editor for beginners or people who don't want to learn a million shortcuts. It was more than sufficient for me for the first few years of my coding career (I'm only now starting to look into more powerful editors, mainly because defining your own syntax highlighting in `nano` can be a bit of a pain.) `nedit` is a small graphical editor, it opens up an X Window and allows point-and-click editing, drag-and-drop, syntax highlighting and more. I use `nedit` sometimes when I want to make small changes to a script and re-run it over and over. Other common CLI (command-line interface) / GUI (graphical user interface) editors include `emacs`, `vi`, `vim`, `gedit`, Notepad++, Atom, and lots more. Some cool ones that I've played around with (and can endorse) include Micro, Light Table, and VS Code. All modern editors offer basic conveniences like search and replace, syntax highlighting, and so on. `vi(m)` and `emacs` have more features than `nano` and `nedit`, but they have a much steeper learning curve. Try a few different editors out and find one that works for you! <a name="creating-and-deleting-files"></a> ## Creating and Deleting Files and Directories <a name="touch"></a> ### `touch` [[ Back to Table of Contents ]](#toc) `touch` was created to modify file timestamps, but it can also be used to quickly create an empty file. You can create a new file by opening it with a text editor, like `nano`: ``` \[ andrew@pc01 前 \]$ ls \[ andrew@pc01 ex \]$ 奈米 a ``` _...editing file..._ ``` \[ andrew@pc01 前 \]$ ls A ``` ...or by simply using `touch`: ``` \[ andrew@pc01 ex \]$ touch b && ls ab ``` > **Bonus**: > > Background a process with \^z (Ctrl+z) > > ```bash > [ andrew@pc01 ex ]$ nano a > ``` > > _...editing file, then hit \^z..._ > > ```bash > Use fg to return to nano > > [1]+ Stopped nano a > [ andrew@pc01 ex ]$ fg > ``` > > _...editing file again..._ --- > **Double Bonus:** > > Kill the current (foreground) process by pressing \^c (Ctrl+c) while it’s running > > Kill a background process with `kill %N` where `N` is the job index shown by the `jobs` command <a name="mkdir-rm-rmdir"></a> ### `mkdir / rm / rmdir` [[ Back to Table of Contents ]](#toc) `mkdir` is used to create new, empty directories: ``` \[ andrew@pc01 ex \]$ ls && mkdir c && ls ab ABC ``` You can remove any file with `rm` -- but be careful, this is non-recoverable! ``` \[ andrew@pc01 ex \]$ rm a && ls 西元前 ``` You can add an _"are you sure?"_ prompt with the `-i` flag: ``` \[ andrew@pc01 前 \]$ rm -ib rm:刪除常規空文件“b”? y ``` Remove an empty directory with `rmdir`. If you `ls -a` in an empty directory, you should only see a reference to the directory itself (`.`) and a reference to its parent directory (`..`): ``` \[ andrew@pc01 ex \]$ rmdir c && ls -a 。 .. ``` `rmdir` removes empty directories only: ``` \[ andrew@pc01 ex \]$ cd .. && ls 測試/ \*.txt 0.txt 1.txt a a.txt bc \[ andrew@pc01 ~ \]$ rmdir 測試/ rmdir:無法刪除“test/”:目錄不為空 ``` ...but you can remove a directory -- and all of its contents -- with `rm -rf` (`-r` = recursive, `-f` = force): ``` \[ andrew@pc01 ~ \]$ rm –rf 測試 ``` <a name="moving-and-copying-files"></a> ## Moving and Copying Files, Making Links, Command History <a name="mv-cp-ln"></a> ### `mv / cp / ln` [[ Back to Table of Contents ]](#toc) `mv` moves / renames a file. You can `mv` a file to a new directory and keep the same file name or `mv` a file to a "new file" (rename it): ``` \[ andrew@pc01 ex \]$ ls && mv ae && ls A B C D BCDE ``` `cp` copies a file: ``` \[ andrew@pc01 ex \]$ cp e e2 && ls BCDE E2 ``` `ln` creates a hard link to a file: ``` ln 的第一個參數是 TARGET,第二個參數是 NEW LINK ================================= \[ andrew@pc01 ex \]$ ln bf && ls bcde e2 f ``` `ln -s` creates a soft link to a file: ``` \[ andrew@pc01 ex \]$ ln -sbg && ls BCDE E2 FG ``` Hard links reference the same actual bytes in memory which contain a file, while soft links refer to the original file name, which itself points to those bytes. [You can read more about soft vs. hard links here.](http://bit.ly/2D0W8cN) <a name="command-history"></a> ### Command History [[ Back to Table of Contents ]](#toc) `bash` has two big features to help you complete and re-run commands, the first is _tab completion_. Simply type the first part of a command, hit the \<tab\> key, and let the terminal guess what you're trying to do: ``` \[ andrew@pc01 目錄 \]$ ls 另一個長檔名 這是一個長檔名 一個新檔名 \[ andrew@pc01 目錄 \]$ ls t ``` _...hit the TAB key after typing `ls t` and the command is completed..._ ``` \[ andrew@pc01 dir \]$ ls 這是檔名 這是長檔名 ``` You may have to hit \<TAB\> multiple times if there's an ambiguity: ``` \[ andrew@pc01 目錄 \]$ ls a \[ andrew@pc01 目錄 \]$ ls an 一個新檔名另一個長檔名 ``` `bash` keeps a short history of the commands you've typed previously and lets you search through those commands by typing \^r (Ctrl+r): ``` \[ andrew@pc01 目錄 \] ``` _...hit \^r (Ctrl+r) to search the command history..._ ``` (反向搜尋)``: ``` _...type 'anew' and the last command containing this is found..._ ``` (reverse-i-search)`anew': 觸碰新檔名 ``` <a name="directory-trees-disk-usage-processes"></a> ## Directory Trees, Disk Usage, and Processes <a name="mkdir--p-tree"></a> ### `mkdir –p / tree` [[ Back to Table of Contents ]](#toc) `mkdir`, by default, only makes a single directory. This means that if, for instance, directory `d/e` doesn't exist, then `d/e/f` can't be made with `mkdir` by itself: ``` \[ andrew@pc01 ex \]$ ls && mkdir d/e/f ABC mkdir:無法建立目錄「d/e/f」:沒有這樣的檔案或目錄 ``` But if we pass the `-p` flag to `mkdir`, it will make all directories in the path if they don't already exist: ``` \[ andrew@pc01 ex \]$ mkdir -pd/e/f && ls A B C D ``` `tree` can help you better visualise a directory's structure by printing a nicely-formatted directory tree. By default, it prints the entire tree structure (beginning with the specified directory), but you can restrict it to a certain number of levels with the `-L` flag: ``` \[ andrew@pc01 前 \]$ 樹 -L 2 。 |-- 一個 |-- b |-- c `--d ``` `--e ``` 3個目錄,2個文件 ``` You can hide empty directories in `tree`'s output with `--prune`. Note that this also removes "recursively empty" directories, or directories which aren't empty _per se_, but which contain only other empty directories, or other recursively empty directories: ``` \[ andrew@pc01 ex \]$ 樹 --prune 。 |-- 一個 `--b ``` <a name="df-du-ps"></a> ### `df / du / ps` [[ Back to Table of Contents ]](#toc) `df` is used to show how much space is taken up by files for the disks or your system (hard drives, etc.). ``` \[ andrew@pc01 前 \]$ df -h 已使用的檔案系統大小 可用 使用% 安裝於 udev 126G 0 126G 0% /dev tmpfs 26G 2.0G 24G 8% /執行 /dev/mapper/ubuntu--vg-root 1.6T 1.3T 252G 84% / … ``` In the above command, `-h` doesn't mean "help", but "human-readable". Some commands use this convention to display file / disk sizes with `K` for kilobytes, `G` for gigabytes, and so on, instead of writing out a gigantic integer number of bytes. `du` shows file space usage for a particular directory and its subdirectories. If you want to know how much space is free on a given hard drive, use `df`; if you want to know how much space a directory is taking up, use `du`: ``` \[ andrew@pc01 ex \]$ 你 4 ./d/e/f 8./d/e 12 ./天 4./c 20 . ``` `du` takes a `--max-depth=N` flag, which only shows directories `N` levels down (or fewer) from the specified directory: ``` \[ andrew@pc01 ex \]$ du -h --max-深度=1 12K./天 4.0K./c 20K。 ``` `ps` shows all of the user's currently-running processes (aka. jobs): ``` \[ andrew@pc01 前 \]$ ps PID TTY 時間 CMD 16642 分/15 00:00:00 ps 25409 點/15 00:00:00 重擊 ``` <a name="basic-misc"></a> ## Miscellaneous <a name="passwd-logout-exit"></a> ### `passwd / logout / exit` [[ Back to Table of Contents ]](#toc) Change your account password with `passwd`. It will ask for your current password for verification, then ask you to enter the new password twice, so you don't make any typos: ``` \[ andrew@pc01 目錄 \]$ 密碼 更改安德魯的密碼。 (目前)UNIX 密碼: 輸入新的 UNIX 密碼: 重新輸入新的 UNIX 密碼: passwd:密碼更新成功 ``` `logout` exits a shell you’ve logged in to (where you have a user account): ``` \[ andrew@pc01 目錄 \]$ 註銷 ────────────────────────────────────────────────── ── ────────────────────────────── 會話已停止 ``` - Press <return> to exit tab ``` ``` - Press R to restart session ``` ``` - Press S to save terminal output to file ``` ``` `exit` exits any kind of shell: ``` \[ andrew@pc01 ~ \]$ 退出 登出 ────────────────────────────────────────────────── ── ────────────────────────────── 會話已停止 ``` - Press <return> to exit tab ``` ``` - Press R to restart session ``` ``` - Press S to save terminal output to file ``` ``` <a name="clear-glob"></a> ### `clear / *` [[ Back to Table of Contents ]](#toc) Run `clear` to move the current terminal line to the top of the screen. This command just adds blank lines below the current prompt line. It's good for clearing your workspace. Use the glob (`*`, aka. Kleene Star, aka. wildcard) when looking for files. Notice the difference between the following two commands: ``` \[ andrew@pc01 ~ \]$ ls Git/Parser/source/ PArrayUtils.java PFile.java PSQLFile.java PWatchman.java PDateTimeUtils.java PFixedWidthFile.java PStringUtils.java PXSVFile.java PDelimitedFile.java PNode.java PTextFile.java Parser.java \[ andrew@pc01 ~ \]$ ls Git/Parser/source/PD\* Git/Parser/source/PDateTimeUtils.java Git/Parser/source/PDelimitedFile.java ``` The glob can be used multiple times in a command and matches zero or more characers: ``` \[ andrew@pc01 ~ \]$ ls Git/Parser/source/P *D* m\* Git/Parser/source/PDateTimeUtils.java Git/Parser/source/PDelimitedFile.java ``` <a name="intermediate"></a> # Intermediate <a name="disk-memory-processor"></a> ## Disk, Memory, and Processor Usage <a name="ncdu"></a> ### `ncdu` [[ Back to Table of Contents ]](#toc) `ncdu` (NCurses Disk Usage) provides a navigable overview of file space usage, like an improved `du`. It opens a read-only `vim`-like window (press `q` to quit): ``` \[ andrew@pc01 ~ \]$ ncdu ncdu 1.11 ~ 使用箭頭鍵導航,按 ?求助 \--- /home/安德魯 ------------------------------------------- ------------------ 148.2 MiB \[##########\] /.m2 91.5 MiB \[######\] /.sbt 79.8 MiB \[######\] /.cache 64.9 MiB \[####\] /.ivy2 40.6 MiB \[##\] /.sdkman 30.2 MiB \[##\] /.local 27.4 MiB \[#\] /.mozilla 24.4 MiB \[#\] /.nanobackups 10.2 MiB \[ \] .confout3.txt ``` 8.4 MiB [ ] /.config ``` ``` 5.9 MiB [ ] /.nbi ``` ``` 5.8 MiB [ ] /.oh-my-zsh ``` ``` 4.3 MiB [ ] /Git ``` ``` 3.7 MiB [ ] /.myshell ``` ``` 1.7 MiB [ ] /jdoc ``` ``` 1.5 MiB [ ] .confout2.txt ``` ``` 1.5 MiB [ ] /.netbeans ``` ``` 1.1 MiB [ ] /.jenv ``` 564.0 KiB \[ \] /.rstudio-desktop 磁碟使用總量:552.7 MiB 表觀大小:523.6 MiB 專案:14618 ``` <a name="top-htop"></a> ### `top / htop` [[ Back to Table of Contents ]](#toc) `top` displays all currently-running processes and their owners, memory usage, and more. `htop` is an improved, interactive `top`. (Note: you can pass the `-u username` flag to restrict the displayed processes to only those owner by `username`.) ``` \[ andrew@pc01 ~ \]$ htop 1 \[ 0.0%\] 9 \[ 0.0%\] 17 \[ 0.0%\] 25 \[ 0.0%\] 2 \[ 0.0%\] 10 \[ 0.0%\] 18 \[ 0.0%\] 26 \[ 0.0%\] 3 \[ 0.0%\] 11 \[ 0.0%\] 19 \[ 0.0%\] 27 \[ 0.0%\] 4 \[ 0.0%\] 12 \[ 0.0%\] 20 \[ 0.0%\] 28 \[ 0.0%\] 5 \[ 0.0%\] 13 \[ 0.0%\] 21 \[| 1.3%\] 29 \[ 0.0%\] 6 \[ 0.0%\] 14 \[ 0.0%\] 22 \[ 0.0%\] 30 \[| 0.6%\] 7 \[ 0.0%\] 15 \[ 0.0%\] 23 \[ 0.0%\] 31 \[ 0.0%\] 8 \[ 0.0%\] 16 \[ 0.0%\] 24 \[ 0.0%\] 32 \[ 0.0%\] Mem\[|||||||||||||||||||1.42G/252G\] 任務:188、366 個; 1 執行 交換電壓\[| 2.47G/256G\]平均負載:0.00 0.00 0.00 ``` Uptime: 432 days(!), 00:03:55 ``` PID USER PRI NI VIRT RES SHR S CPU% MEM% TIME+ 指令 9389 安德魯 20 0 23344 3848 2848 R 1.3 0.0 0:00.10 htop 10103 根 20 0 3216M 17896 2444 S 0.7 0.0 5h48:56 /usr/bin/dockerd ``` 1 root 20 0 181M 4604 2972 S 0.0 0.0 15:29.66 /lib/systemd/syst ``` 533 根 20 0 44676 6908 6716 S 0.0 0.0 11:19.77 /lib/systemd/syst 546 根 20 0 244M 0 0 S 0.0 0.0 0:01.39 /sbin/lvmetad -f 1526 根 20 0 329M 2252 1916 S 0.0 0.0 0:00.00 /usr/sbin/ModemMa 1544 根 20 0 329M 2252 1916 S 0.0 0.0 0:00.06 /usr/sbin/ModemMa F1Help F2Setup F3SearchF4FilterF5Tree F6SortByF7Nice -F8Nice +F9Kill F10Quit ``` <a name="REPLs-software-versions"></a> ## REPLs and Software Versions <a name="REPLs"></a> ### REPLs [[ Back to Table of Contents ]](#toc) A **REPL** is a Read-Evaluate-Print Loop, similar to the command line, but usually used for particular programming languages. You can open the Python REPL with the `python` command (and quit with the `quit()` function): ``` \[ andrew@pc01 ~ \]$ python Python 3.5.2(默認,2018 年 11 月 12 日,13:43:14)... > > > 辭職() ``` Open the R REPL with the `R` command (and quit with the `q()` function): ``` \[ andrew@pc01 ~ \]$ R R版3.5.2(2018-12-20)--「蛋殼冰屋」... > q() 儲存工作區影像? \[是/否/c\]: 否 ``` Open the Scala REPL with the `scala` command (and quit with the `:quit` command): ``` \[ andrew@pc01 ~ \]$ scala 歡迎使用 Scala 2.11.12 ... 斯卡拉>:退出 ``` Open the Java REPL with the `jshell` command (and quit with the `/exit` command): ``` \[ andrew@pc01 ~ \]$ jshell |歡迎使用 JShell——版本 11.0.1 ... jshell> /退出 ``` Alternatively, you can exit any of these REPLs with \^d (Ctrl+d). \^d is the EOF (end of file) marker on Unix and signifies the end of input. <a name="version"></a> ### `-version / --version / -v` [[ Back to Table of Contents ]](#toc) Most commands and programs have a `-version` or `--version` flag which gives the software version of that command or program. Most applications make this information easily available: ``` \[ andrew@pc01 ~ \]$ ls --version ls (GNU coreutils) 8.25 ... \[ andrew@pc01 ~ \]$ ncdu -版本 NCDU 1.11 \[ andrew@pc01 ~ \]$ python --version Python 3.5.2 ``` ...but some are less intuitive: ``` \[ andrew@pc01 ~ \]$ sbt scalaVersion … \[資訊\]2.12.4 ``` Note that some programs use `-v` as a version flag, while others use `-v` to mean "verbose", which will run the application while printing lots of diagnostic or debugging information: ``` SCP(1) BSD 通用指令手冊 SCP(1) 姓名 ``` scp -- secure copy (remote file copy program) ``` … -v 詳細模式。導致 scp 和 ssh(1) 列印偵錯訊息 ``` about their progress. This is helpful in debugging connection, ``` ``` authentication, and configuration problems. ``` … ``` <a name="env-vars-aliases"></a> ## Environment Variables and Aliases <a name="env-vars"></a> ### Environment Variables [[ Back to Table of Contents ]](#toc) **Environment variables** (sometimes shortened to "env vars") are persistent variables that can be created and used within your `bash` shell. They are defined with an equals sign (`=`) and used with a dollar sign (`$`). You can see all currently-defined env vars with `printenv`: ``` \[ andrew@pc01 ~ \]$ printenv SPARK\_HOME=/usr/local/spark 術語=xterm … ``` Set a new environment variable with an `=` sign (don't put any spaces before or after the `=`, though!): ``` \[ andrew@pc01 ~ \]$ myvar=你好 ``` Print a specific env var to the terminal with `echo` and a preceding `$` sign: ``` \[ andrew@pc01 ~ \]$ echo $myvar 你好 ``` Environment variables which contain spaces or other whitespace should be surrounded by quotes (`"..."`). Note that reassigning a value to an env var overwrites it without warning: ``` \[ andrew@pc01 ~ \]$ myvar="你好,世界!" && 回顯 $myvar 你好世界! ``` Env vars can also be defined using the `export` command. When defined this way, they will also be available to sub-processes (commands called from this shell): ``` \[ andrew@pc01 ~ \]$ export myvar="另一" && echo $myvar 另一個 ``` You can unset an environment variable by leaving the right-hand side of the `=` blank or by using the `unset` command: ``` \[ andrew@pc01 ~ \]$ 取消設定 mynewvar \[ andrew@pc01 ~ \]$ echo $mynewvar ``` <a name="aliases"></a> ### Aliases [[ Back to Table of Contents ]](#toc) **Aliases** are similar to environment variables but are usually used in a different way -- to replace long commands with shorter ones: ``` \[ andrew@pc01 apidocs \]$ ls -l -a -h -t 總計 220K drwxr-xr-x 5 安德魯 安德魯 4.0K 12 月 21 日 12:37 。 -rw-r--r-- 1 安德魯 安德魯 9.9K 十二月 21 12:37 help-doc.html -rw-r--r-- 1 安德魯 安德魯 4.5K 12 月 21 日 12:37 script.js … \[ andrew@pc01 apidocs \]$ 別名 lc="ls -l -a -h -t" \[ andrew@pc01 apidocs \]$ lc 總計 220K drwxr-xr-x 5 安德魯 安德魯 4.0K 12 月 21 日 12:37 。 -rw-r--r-- 1 安德魯 安德魯 9.9K 十二月 21 12:37 help-doc.html -rw-r--r-- 1 安德魯 安德魯 4.5K 12 月 21 日 12:37 script.js … ``` You can remove an alias with `unalias`: ``` \[ andrew@pc01 apidocs \]$ unalias lc \[ andrew@pc01 apidocs \]$ lc 目前未安裝程式“lc”。 … ``` > **Bonus:** > > [Read about the subtle differences between environment variables and aliases here.](http://bit.ly/2TDG8Tx) > > [Some programs, like **git**, allow you to define aliases specifically for that software.](http://bit.ly/2TG8X1A) <a name="basic-bash-scripting"></a> ## Basic `bash` Scripting <a name="bash-scripts"></a> ### `bash` Scripts [[ Back to Table of Contents ]](#toc) `bash` scripts (usually ending in `.sh`) allow you to automate complicated processes, packaging them into reusable functions. A `bash` script can contain any number of normal shell commands: ``` \[ andrew@pc01 ~ \]$ echo "ls && touch file && ls" > ex.sh ``` A shell script can be executed with the `source` command or the `sh` command: ``` \[ andrew@pc01 ~ \]$ 源 ex.sh 桌面 Git TEST c ex.sh 專案測試 桌面 Git TEST c ex.sh 檔案專案測試 ``` Shell scripts can be made executable with the `chmod` command (more on this later): ``` \[ andrew@pc01 ~ \]$ echo "ls && touch file2 && ls" > ex2.sh \[ andrew@pc01 ~ \]$ chmod +x ex2.sh ``` An executable shell script can be run by preceding it with `./`: ``` \[ andrew@pc01 ~ \]$ ./ex2.sh 桌面 Git TEST c ex.sh ex2.sh 檔案專案測試 桌面 Git TEST c ex.sh ex2.sh 檔案 file2 專案測試 ``` Long lines of code can be split by ending a command with `\`: ``` \[ andrew@pc01 ~ \]$ echo "for i in {1..3}; do echo \\ > \\"歡迎\\$i次\\";完成” > ex3.sh ``` Bash scripts can contain loops, functions, and more! ``` \[ andrew@pc01 ~ \]$ 源 ex3.sh 歡迎1次 歡迎2次 歡迎3次 ``` <a name="custom-prompt-ls"></a> ### Custom Prompt and `ls` [[ Back to Table of Contents ]](#toc) Bash scripting can make your life a whole lot easier and more colourful. [Check out this great bash scripting cheat sheet.](https://devhints.io/bash) `$PS1` (Prompt String 1) is the environment variable that defines your main shell prompt ([learn about the other prompts here](http://bit.ly/2SPgsmT)): ``` \[ andrew@pc01 ~ \]$ printf "%q" $PS1 $'\\n\\\[\\E\[1m\\\]\\\[\\E\[30m\\\]\\A'$'\\\[\\E\[37m\\\]|\\\[\\E\[36m\\\]\\u\\\[\\E\[37m \\\]@\\\[\\E\[34m\\\]\\h'$'\\\[\\E\[32m\\\]\\W\\\[\\E\[37m\\\]|'$'\\\[\\E(B\\E\[m\\\] ' ``` You can change your default prompt with the `export` command: ``` \[ andrew@pc01 ~ \]$ export PS1="\\n此處指令> " 此處指令> echo $PS1 \\n此處指令> ``` ...[you can add colours, too!](http://bit.ly/2TMbEit): ``` 此處指令> export PS1="\\e\[1;31m\\n程式碼: \\e\[39m" (這應該是紅色的,但在 Markdown 中可能不會這樣顯示) =============================== 程式碼:回顯$PS1 \\e\[1;31m\\n程式碼: \\e\[39m ``` You can also change the colours shown by `ls` by editing the `$LS_COLORS` environment variable: ``` (同樣,這些顏色可能不會出現在 Markdown 中) =========================== 程式碼:ls 桌面 Git TEST c ex.sh ex2.sh ex3.sh 檔案 file2 專案測試 程式碼:匯出 LS\_COLORS='di=31:fi=0:ln=96:or=31:mi=31:ex=92' 程式碼:ls 桌面 Git TEST c ex.sh ex2.sh ex3.sh 檔案 file2 專案測試 ``` <a name="config-files"></a> ## Config Files <a name="config-bashrc"></a> ### Config Files / `.bashrc` [[ Back to Table of Contents ]](#toc) If you tried the commands in the last section and logged out and back in, you may have noticed that your changes disappeared. _config_ (configuration) files let you maintain settings for your shell or for a particular program every time you log in (or run that program). The main configuration file for a `bash` shell is the `~/.bashrc` file. Aliases, environment variables, and functions added to `~/.bashrc` will be available every time you log in. Commands in `~/.bashrc` will be run every time you log in. If you edit your `~/.bashrc` file, you can reload it without logging out by using the `source` command: ``` \[ andrew@pc01 ~ \]$ nano ~/.bashrc ``` _...add the line `echo “~/.bashrc loaded!”` to the top of the file_... ``` \[ andrew@pc01 ~ \]$ 源 ~/.bashrc ~/.bashrc 已載入! ``` _...log out and log back in..._ ``` 最後登入:2019 年 1 月 11 日星期五 10:29:07 從 111.11.11.111 ~/.bashrc 已加載! \[ 安德魯@pc01 ~ \] ``` <a name="types-of-shells"></a> ### Types of Shells [[ Back to Table of Contents ]](#toc) _Login_ shells are shells you log in to (where you have a username). _Interactive_ shells are shells which accept commands. Shells can be login and interactive, non-login and non-interactive, or any other combination. In addition to `~/.bashrc`, there are a few other scripts which are `sourced` by the shell automatically when you log in or log out. These are: - `/etc/profile` - `~/.bash_profile` - `~/.bash_login` - `~/.profile` - `~/.bash_logout` - `/etc/bash.bash_logout` Which of these scripts are sourced, and the order in which they're sourced, depend on the type of shell opened. See [the bash man page](https://linux.die.net/man/1/bash) and [these](http://bit.ly/2TGCwA8) Stack Overflow [posts](http://bit.ly/2TFHFsf) for more information. Note that `bash` scripts can `source` other scripts. For instance, in your `~/.bashrc`, you could include the line: ``` 來源~/.bashrc\_addl ``` ...which would also `source` that `.bashrc_addl` script. This file can contain its own aliases, functions, environment variables, and so on. It could, in turn, `source` other scripts, as well. (Be careful to avoid infinite loops of script-sourcing!) It may be helpful to split commands into different shell scripts based on functionality or machine type (Ubuntu vs. Red Hat vs. macOS), for example: - `~/.bash_ubuntu` -- configuration specific to Ubuntu-based machines - `~/.bashrc_styles` -- aesthetic settings, like `PS1` and `LS_COLORS` - `~/.bash_java` -- configuration specific to the Java language I try to keep separate `bash` files for aesthetic configurations and OS- or machine-specific code, and then I have one big `bash` file containing shortcuts, etc. that I use on every machine and every OS. Note that there are also _different shells_. `bash` is just one kind of shell (the "Bourne Again Shell"). Other common ones include `zsh`, `csh`, `fish`, and more. Play around with different shells and find one that's right for you, but be aware that this tutorial contains `bash` shell commands only and not everything listed here (maybe none of it) will be applicable to shells other than `bash`. <a name="finding-things"></a> ## Finding Things <a name="whereis-which-whatis"></a> ### `whereis / which / whatis` [[ Back to Table of Contents ]](#toc) `whereis` searches for "possibly useful" files related to a particular command. It will attempt to return the location of the binary (executable machine code), source (code source files), and `man` page for that command: ``` \[ andrew@pc01 ~ \]$ whereis ls ls: /bin/ls /usr/share/man/man1/ls.1.gz ``` `which` will only return the location of the binary (the command itself): ``` \[ andrew@pc01 ~ \]$ 其中 ls /bin/ls ``` `whatis` prints out the one-line description of a command from its `man` page: ``` \[ andrew@pc01 ~ \]$ 什麼是哪裡是哪個什麼是 whereis (1) - 尋找指令的二進位、原始檔和手冊頁文件 which (1) - 定位指令 Whatis (1) - 顯示一行手冊頁描述 ``` `which` is useful for finding the "original version" of a command which may be hidden by an alias: ``` \[ andrew@pc01 ~ \]$ 別名 ls="ls -l" “original” ls 已被上面定義的別名“隱藏” =========================== \[ andrew@pc01 ~ \]$ ls 總計 36 drwxr-xr-x 2 安德魯 andrew 4096 Jan 9 14:47 桌面 drwxr-xr-x 4 安德魯 安德魯 4096 十二月 6 10:43 Git … 但我們仍然可以使用返回的位置來呼叫「原始」ls ======================= \[ andrew@pc01 ~ \]$ /bin/ls 桌面 Git TEST c ex.sh ex2.sh ex3.sh 檔案 file2 專案測試 ``` <a name="locate-find"></a> ### `locate / find` [[ Back to Table of Contents ]](#toc) `locate` finds a file anywhere on the system by referring to a semi-regularly-updated cached list of files: ``` \[ andrew@pc01 ~ \]$ 找到 README.md /home/andrew/.config/micro/plugins/gotham-colors/README.md /home/andrew/.jenv/README.md /home/andrew/.myshell/README.md … ``` Because it's just searching a list, `locate` is usually faster than the alternative, `find`. `find` iterates through the file system to find the file you're looking for. Because it's actually looking at the files which _currently_ exist on the system, though, it will always return an up-to-date list of files, which is not necessarily true with `locate`. ``` \[ andrew@pc01 ~ \]$ find ~/ -iname "README.md" /home/andrew/.jenv/README.md /home/andrew/.config/micro/plugins/gotham-colors/README.md /home/andrew/.oh-my-zsh/plugins/ant/README.md … ``` `find` was written for the very first version of Unix in 1971, and is therefore much more widely available than `locate`, which was added to GNU in 1994. `find` has many more features than `locate`, and can search by file age, size, ownership, type, timestamp, permissions, depth within the file system; `find` can search using regular expressions, execute commands on files it finds, and more. When you need a fast (but possibly outdated) list of files, or you’re not sure what directory a particular file is in, use `locate`. When you need an accurate file list, maybe based on something other than the files’ names, and you need to do something with those files, use `find`. <a name="downloading-things"></a> ## Downloading Things <a name="ping-wget-curl"></a> ### `ping / wget / curl` [[ Back to Table of Contents ]](#toc) `ping` attempts to open a line of communication with a network host. Mainly, it's used to check whether or not your Internet connection is down: ``` \[ andrew@pc01 ~ \]$ ping google.com PING google.com (74.125.193.100) 56(84) 位元組資料。 使用 32 位元組資料 Ping 74.125.193.100: 來自 74.125.193.100 的回覆:位元組=32 時間<1ms TTL=64 … ``` `wget` is used to easily download a file from the Internet: ``` \[ andrew@pc01 ~ \]$ wget \\ > http://releases.ubuntu.com/18.10/ubuntu-18.10-desktop-amd64.iso ``` `curl` can be used just like `wget` (don’t forget the `--output` flag): ``` \[ andrew@pc01 ~ \]$ 捲曲 \\ > http://releases.ubuntu.com/18.10/ubuntu-18.10-desktop-amd64.iso \\ > \--輸出ubuntu.iso ``` `curl` and `wget` have their own strengths and weaknesses. `curl` supports many more protocols and is more widely available than `wget`; `curl` can also send data, while `wget` can only receive data. `wget` can download files recursively, while `curl` cannot. In general, I use `wget` when I need to download things from the Internet. I don’t often need to send data using `curl`, but it’s good to be aware of it for the rare occasion that you do. <a name="apt-gunzip-tar-gzip"></a> ### `apt / gunzip / tar / gzip` [[ Back to Table of Contents ]](#toc) Debian-descended Linux distributions have a fantastic package management tool called `apt`. It can be used to install, upgrade, or delete software on your machine. To search `apt` for a particular piece of software, use `apt search`, and install it with `apt install`: ``` \[ andrew@pc01 ~ \]$ apt 搜尋漂白位 ...bleachbit/bionic、bionic 2.0-2 全部 從系統中刪除不需要的文件 您需要“sudo”來安裝軟體 ============== \[ andrew@pc01 ~ \]$ sudo apt installbleachbit ``` Linux software often comes packaged in `.tar.gz` ("tarball") files: ``` \[ andrew@pc01 ~ \]$ wget \\ > https://github.com/atom/atom/releases/download/v1.35.0-beta0/atom-amd64.tar.gz ``` ...these types of files can be unzipped with `gunzip`: ``` \[ andrew@pc01 ~ \]$gunzipatom-amd64.tar.gz && ls 原子 amd64.tar ``` A `.tar.gz` file will be `gunzip`-ped to a `.tar` file, which can be extracted to a directory of files using `tar -xf` (`-x` for "extract", `-f` to specify the file to "untar"): ``` \[ andrew@pc01 ~ \]$ tar -xfatom-amd64.tar && mv \\ 原子-beta-1.35.0-beta0-amd64 原子 && ls 原子atom-amd64.tar ``` To go in the reverse direction, you can create (`-c`) a tar file from a directory and zip it (or unzip it, as appropriate) with `-z`: ``` \[ andrew@pc01 ~ \]$ tar -zcf 壓縮.tar.gz 原子 && ls 原子atom-amd64.tar壓縮.tar.gz ``` `.tar` files can also be zipped with `gzip`: ``` \[ andrew@pc01 ~ \]$ gzipatom-amd64.tar && ls 原子 原子-amd64.tar.gz 壓縮.tar.gz ``` <a name="redirecting-io"></a> ## Redirecting Input and Output <a name="pipe-gt-lt-echo-printf"></a> ### `| / > / < / echo / printf` [[ Back to Table of Contents ]](#toc) By default, shell commands read their input from the standard input stream (aka. stdin or 0) and write to the standard output stream (aka. stdout or 1), unless there’s an error, which is written to the standard error stream (aka. stderr or 2). `echo` writes text to stdout by default, which in most cases will simply print it to the terminal: ``` \[ andrew@pc01 ~ \]$ 回顯“你好” 你好 ``` The pipe operator, `|`, redirects the output of the first command to the input of the second command: ``` 'wc'(字數)傳回檔案中的行數、字數、位元組數 ======================== \[ andrew@pc01 ~ \]$ echo "範例文件" |廁所 ``` 1 2 17 ``` ``` `>` redirects output from stdout to a particular location ``` \[ andrew@pc01 ~ \]$ echo "test" > 文件 && 頭文件 測試 ``` `printf` is an improved `echo`, allowing formatting and escape sequences: ``` \[ andrew@pc01 ~ \]$ printf "1\\n3\\n2" 1 3 2 ``` `<` gets input from a particular location, rather than stdin: ``` 'sort' 依字母/數字順序對檔案的行進行排序 ======================== \[ andrew@pc01 ~ \]$ sort <(printf "1\\n3\\n2") 1 2 3 ``` Rather than a [UUOC](#viewing-and-editing-files), the recommended way to send the contents of a file to a command is to use `<`. Note that this causes data to "flow" right-to-left on the command line, rather than (the perhaps more natural, for English-speakers) left-to-right: ``` \[ andrew@pc01 ~ \]$ printf "1\\n3\\n2" > 文件 && 排序 < 文件 1 2 3 ``` <a name="std-tee"></a> ### `0 / 1 / 2 / tee` [[ Back to Table of Contents ]](#toc) 0, 1, and 2 are the standard input, output, and error streams, respectively. Input and output streams can be redirected with the `|`, `>`, and `<` operators mentioned previously, but stdin, stdout, and stderr can also be manipulated directly using their numeric identifiers: Write to stdout or stderr with `>&1` or `>&2`: ``` \[ andrew@pc01 ~ \]$ 貓測試 回顯“標準輸出”>&1 回顯“標準錯誤”>&2 ``` By default, stdout and stderr both print output to the terminal: ``` \[ andrew@pc01 ~ \]$ ./測試 標準錯誤 標準輸出 ``` Redirect stdout to `/dev/null` (only print output sent to stderr): ``` \[ andrew@pc01 ~ \]$ ./test 1>/dev/null 標準錯誤 ``` Redirect stderr to `/dev/null` (only print output sent to stdout): ``` \[ andrew@pc01 ~ \]$ ./test 2>/dev/null 標準輸出 ``` Redirect all output to `/dev/null` (print nothing): ``` \[ andrew@pc01 ~ \]$ ./test &>/dev/null ``` Send output to stdout and any number of additional locations with `tee`: ``` \[ andrew@pc01 ~ \]$ ls && echo "測試" | tee 文件1 文件2 文件3 && ls 文件0 測試 文件0 文件1 文件2 文件3 ``` <a name="advanced"></a> # Advanced <a name="superuser"></a> ## Superuser <a name="sudo-su"></a> ### `sudo / su` [[ Back to Table of Contents ]](#toc) You can check what your username is with `whoami`: ``` \[ andrew@pc01 abc \]$ whoami 安德魯 ``` ...and run a command as another user with `sudo -u username` (you will need that user's password): ``` \[ andrew@pc01 abc \]$ sudo -u 測試觸摸 def && ls -l 總計 0 -rw-r--r-- 1 次測試 0 Jan 11 20:05 def ``` If `–u` is not provided, the default user is the superuser (usually called "root"), with unlimited permissions: ``` \[ andrew@pc01 abc \]$ sudo touch ghi && ls -l 總計 0 -rw-r--r-- 1 次測試 0 Jan 11 20:05 def -rw-r--r-- 1 root root 0 Jan 11 20:14 ghi ``` Use `su` to become another user temporarily (and `exit` to switch back): ``` \[ andrew@pc01 abc \]$ su 測試 密碼: test@pc01:/home/andrew/abc$ whoami 測試 test@pc01:/home/andrew/abc$ 退出 出口 \[ andrew@pc01 abc \]$ whoami 安德魯 ``` [Learn more about the differences between `sudo` and `su` here.](http://bit.ly/2SKQH77) <a name="click-click"></a> ### `!!` [[ Back to Table of Contents ]](#toc) The superuser (usually "root") is the only person who can install software, create users, and so on. Sometimes it's easy to forget that, and you may get an error: ``` \[ andrew@pc01 ~ \]$ apt 安裝 ruby E:無法開啟鎖定檔案 /var/lib/dpkg/lock-frontend - 開啟(13:權限被拒絕) E: 無法取得 dpkg 前端鎖定 (/var/lib/dpkg/lock-frontend),您是 root 嗎? ``` You could retype the command and add `sudo` at the front of it (run it as the superuser): ``` \[ andrew@pc01 ~ \]$ sudo apt install ruby 正在閱讀包裝清單... ``` Or, you could use the `!!` shortcut, which retains the previous command: ``` \[ andrew@pc01 ~ \]$ apt 安裝 ruby E:無法開啟鎖定檔案 /var/lib/dpkg/lock-frontend - 開啟(13:權限被拒絕) E: 無法取得 dpkg 前端鎖定 (/var/lib/dpkg/lock-frontend),您是 root 嗎? \[ andrew@pc01 ~ \]$ sudo !! sudo apt 安裝 ruby 正在閱讀包裝清單... ``` By default, running a command with `sudo` (and correctly entering the password) allows the user to run superuser commands for the next 15 minutes. Once those 15 minutes are up, the user will again be prompted to enter the superuser password if they try to run a restricted command. <a name="file-permissions"></a> ## File Permissions <a name="file-permissions-sub"></a> ### File Permissions [[ Back to Table of Contents ]](#toc) Files may be able to be read (`r`), written to (`w`), and/or executed (`x`) by different users or groups of users, or not at all. File permissions can be seen with the `ls -l` command and are represented by 10 characters: ``` \[ andrew@pc01 ~ \]$ ls -lh 總計 8 drwxr-xr-x 4 安德魯 安德魯 4.0K 1 月 4 日 19:37 品嚐 -rwxr-xr-x 1 安德魯 安德魯 40 Jan 11 16:16 測試 -rw-r--r-- 1 安德魯 安德魯 0 一月 11 16:34 tist ``` The first character of each line represents the type of file, (`d` = directory, `l` = link, `-` = regular file, and so on); then there are three groups of three characters which represent the permissions held by the user (u) who owns the file, the permissions held by the group (g) which owns the file, and the permissions held any other (o) users. (The number which follows this string of characters is the number of links in the file system to that file (4 or 1 above).) `r` means that person / those people have read permission, `w` is write permission, `x` is execute permission. If a directory is “executable”, that means it can be opened and its contents can be listed. These three permissions are often represented with a single three-digit number, where, if `x` is enabled, the number is incremented by 1, if `w` is enabled, the number is incremented by 2, and if `r` is enabled, the number is incremented by 4. Note that these are equivalent to binary digits (`r-x` -> `101` -> `5`, for example). So the above three files have permissions of 755, 755, and 644, respectively. The next two strings in each list are the name of the owner (`andrew`, in this case) and the group of the owner (also `andrew`, in this case). Then comes the size of the file, its most recent modification time, and its name. The `–h` flag makes the output human readable (i.e. printing `4.0K` instead of `4096` bytes). <a name="chmod-chown"></a> ### `chmod / chown` [[ Back to Table of Contents ]](#toc) File permissions can be modified with `chmod` by setting the access bits: ``` \[ andrew@pc01 ~ \]$ chmod 777 測試 && chmod 000 tit && ls -lh 總計 8.0K drwxr-xr-x 4 安德魯 安德魯 4.0K 1 月 4 日 19:37 品嚐 -rwxrwxrwx 1 安德魯 安德魯 40 Jan 11 16:16 測試 \---------- 1 安德魯 安德魯 0 一月 11 16:34 tist ``` ...or by adding (`+`) or removing (`-`) `r`, `w`, and `x` permissions with flags: ``` \[ andrew@pc01 ~ \]$ chmod +rwx Tist && chmod -w 測試 && ls -lh chmod:測試:新權限是 r-xrwxrwx,而不是 r-xr-xr-x 總計 8.0K drwxr-xr-x 4 安德魯 安德魯 4.0K 1 月 4 日 19:37 品嚐 -r-xrwxrwx 1 安德魯 安德魯 40 Jan 11 16:16 測試 -rwxr-xr-x 1 安德魯 安德魯 0 一月 11 16:34 tist ``` The user who owns a file can be changed with `chown`: ``` \[ andrew@pc01 ~ \]$ sudo chown 碼頭測試 ``` The group which owns a file can be changed with `chgrp`: ``` \[ andrew@pc01 ~ \]$ sudo chgrp hadoop tit && ls -lh 總計 8.0K drwxr-xr-x 4 安德魯 安德魯 4.0K 1 月 4 日 19:37 品嚐 \-----w--w- 1 瑪麗娜·安德魯 2011 年 1 月 40 日 16:16 測試 -rwxr-xr-x 1 安德魯 hadoop 0 一月 11 16:34 tist ``` <a name="users-groups"></a> ## User and Group Management <a name="users"></a> ### Users [[ Back to Table of Contents ]](#toc) `users` shows all users currently logged in. Note that a user can be logged in multiple times if -- for instance -- they're connected via multiple `ssh` sessions. ``` \[ andrew@pc01 ~ \]$ 用戶 安德魯·科林·科林·科林·科林·科林·克里希納·克里希納 ``` To see all users (even those not logged in), check `/etc/passwd`. (**WARNING**: do not modify this file! You can corrupt your user accounts and make it impossible to log in to your system.) ``` \[ andrew@pc01 ~ \]$ alias au="cut -d: -f1 /etc/passwd \\ > |排序| uniq”&& au \_易於 一個廣告 安德魯... ``` Add a user with `useradd`: ``` \[ andrew@pc01 ~ \]$ sudo useradd aardvark && au \_易於 土豚 一個廣告... ``` Delete a user with `userdel`: ``` \[ andrew@pc01 ~ \]$ sudo userdel aardvark && au \_易於 一個廣告 安德魯... ``` [Change a user’s default shell, username, password, or group membership with `usermod`.](http://bit.ly/2D4upIg) <a name="groups"></a> ### Groups [[ Back to Table of Contents ]](#toc) `groups` shows all of the groups of which the current user is a member: ``` \[ andrew@pc01 ~ \]$ 組 andrew adm cdrom sudo dial plugdev lpadmin sambashare hadoop ``` To see all groups on the system, check `/etc/group`. (**DO NOT MODIFY** this file unless you know what you are doing.) ``` \[ andrew@pc01 ~ \]$ alias ag=“cut -d: -f1 /etc/group \\ > |排序”&& ag 管理員 一個廣告 安德魯... ``` Add a group with `groupadd`: ``` \[ andrew@pc01 ~ \]$ sudo groupadd aardvark && ag 土豚 管理員 一個廣告... ``` Delete a group with `groupdel`: ``` \[ andrew@pc01 ~ \]$ sudo groupdel aardvark && ag 管理員 一個廣告 安德魯... ``` [Change a group’s name, ID number, or password with `groupmod`.](https://linux.die.net/man/8/groupmod) <a name="text-processing"></a> ## Text Processing <a name="uniq-sort-diff-cmp"></a> ### `uniq / sort / diff / cmp` [[ Back to Table of Contents ]](#toc) `uniq` can print unique lines (default) or repeated lines: ``` \[ andrew@pc01 man \]$ printf "1\\n2\\n2" > a && \\ > printf "1\\n3\\n2" > b \[ andrew@pc01 人 \]$ uniq a 1 2 ``` `sort` will sort lines alphabetically / numerically: ``` \[ andrew@pc01 man \]$ 排序 b 1 2 3 ``` `diff` will report which lines differ between two files: ``` \[ andrew@pc01 人 \]$ diff ab 2c2 < 2 --- > 3 ``` `cmp` reports which bytes differ between two files: ``` \[andrew@pc01 人\]$ cmp ab ab 不同:字元 3,第 2 行 ``` <a name="cut-sed"></a> ### `cut / sed` [[ Back to Table of Contents ]](#toc) `cut` is usually used to cut a line into sections on some delimiter (good for CSV processing). `-d` specifies the delimiter and `-f` specifies the field index to print (starting with 1 for the first field): ``` \[ andrew@pc01 人 \]$ printf "137.99.234.23" > c \[ andrew@pc01 man \]$ cut -d'.' c-f1 137 ``` `sed` is commonly used to replace a string with another string in a file: ``` \[ andrew@pc01 man \]$ echo "舊" | sed s/舊/新/ 新的 ``` ...but `sed` is an extremely powerful utility, and cannot be properly summarised here. It’s actually Turing-complete, so it can do anything that any other programming language can do. `sed` can find and replace based on regular expressions, selectively print lines of a file which match or contain a certain pattern, edit text files in-place and non-interactively, and much more. A few good tutorials on `sed` include: - [https://www.tutorialspoint.com/sed/](https://www.tutorialspoint.com/sed/) - [http://www.grymoire.com/Unix/Sed.html](http://www.grymoire.com/Unix/Sed.html) - [https://www.computerhope.com/unix/used.htm](https://www.computerhope.com/unix/used.htm) <a name="pattern-matching"></a> ## Pattern Matching <a name="grep"></a> ### `grep` [[ Back to Table of Contents ]](#toc) The name `grep` comes from `g`/`re`/`p` (search `g`lobally for a `r`egular `e`xpression and `p`rint it); it’s used for finding text in files. `grep` is used to find lines of a file which match some pattern: ``` \[ andrew@pc01 ~ \]$ grep -e " *.fi.* " /etc/profile /etc/profile:Bourne shell 的系統範圍 .profile 檔案 (sh(1)) =================================================== ``` # The file bash.bashrc already sets the default PS1. ``` ``` fi ``` ``` fi ``` … ``` ...or contain some word: ``` \[ andrew@pc01 ~ \]$ grep "andrew" /etc/passwd 安德魯:x:1000:1000:安德魯,,,:/home/andrew:/bin/bash ``` `grep` is usually the go-to choice for simply finding matching lines in a file, if you’re planning on allowing some other program to handle those lines (or if you just want to view them). `grep` allows for (`-E`) use of extended regular expressions, (`-F`) matching any one of multiple strings at once, and (`-r`) recursively searching files within a directory. These flags used to be implemented as separate commands (`egrep`, `fgrep`, and `rgrep`, respectively), but those commands are now deprecated. > **Bonus**: [see the origins of the names of a few famous `bash` commands](https://kb.iu.edu/d/abnd) <a name="awk"></a> ### `awk` [[ Back to Table of Contents ]](#toc) `awk` is a pattern-matching language built around reading and manipulating delimited data files, like CSV files. As a rule of thumb, `grep` is good for finding strings and patterns in files, `sed` is good for one-to-one replacement of strings in files, and `awk` is good for extracting strings and patterns from files and analysing them. As an example of what `awk` can do, here’s a file containing two columns of data: ``` \[ andrew@pc01 ~ \]$ printf "A 10\\nB 20\\nC 60" > 文件 ``` Loop over the lines, add the number to sum, increment count, print the average: ``` \[ andrew@pc01 ~ \]$ awk 'BEGIN {sum=0;計數=0; OFS=“”} {sum+=$2; count++} END {print "平均值:", sum/count}' 文件 平均:30 ``` `sed` and `awk` are both Turing-complete languages. There have been multiple books written about each of them. They can be extremely useful with pattern matching and text processing. I really don’t have enough space here to do either of them justice. Go read more about them! > **Bonus**: [learn about some of the differences between `sed`, `grep`, and `awk`](http://bit.ly/2AI3IaN) <a name="ssh"></a> ## Copying Files Over `ssh` <a name="ssh-scp"></a> ### `ssh / scp` [[ Back to Table of Contents ]](#toc) `ssh` is how Unix-based machines connect to each other over a network: ``` \[ andrew@pc01 ~ \]$ ssh –p安德魯@137.xxx.xxx.89 上次登入:2019 年 1 月 11 日星期五 12:30:52,來自 137.xxx.xxx.199 ``` Notice that my prompt has changed as I’m now on a different machine: ``` \[ andrew@pc02 ~ \]$ 退出 登出 與 137.xxx.xxx.89 的連線已關閉。 ``` Create a file on machine 1: ``` \[ andrew@pc01 ~ \]$ echo "你好" > 你好 ``` Copy it to machine 2 using `scp` (secure copy; note that `scp` uses `–P` for a port #, `ssh` uses `–p`) ``` \[ andrew@pc01 ~ \]$ scp –P你好安德魯@137.xxx.xxx.89:~ 你好 100% 0 0.0KB/秒 00:00 ``` `ssh` into machine 2: ``` \[ andrew@pc02 ~ \]$ ssh –p安德魯@137.xxx.xxx.89 上次登入:2019 年 1 月 11 日星期五 22:47:37,來自 137.xxx.xxx.79 ``` The file’s there! ``` \[ andrew@pc02 ~ \]$ ls 你好多xargs \[ andrew@pc02 ~ \]$ 貓你好 你好 ``` <a name="rsync"></a> ### `rsync` [[ Back to Table of Contents ]](#toc) `rsync` is a file-copying tool which minimises the amount of data copied by looking for deltas (changes) between files. Suppose we have two directories: `d`, with one file, and `s`, with two files: ``` \[ andrew@pc01 d \]$ ls && ls ../s f0 f0 f1 ``` Sync the directories (copying only missing data) with `rsync`: ``` \[ andrew@pc01 d \]$ rsync -off ../s/\* . 正在發送增量文件列表... ``` `d` now contains all files that `s` contains: ``` \[ andrew@pc01 d \]$ ls f0 f1 ``` `rsync` can be performed over `ssh` as well: ``` \[ andrew@pc02 r \]$ ls \[ andrew@pc02 r \]$ rsync -avz -e "ssh -p “ [email protected]:~/s/\* 。 接收增量檔案列表 f0 f1 發送 62 位元組 接收 150 位元組 141.33 位元組/秒 總大小為 0 加速率為 0.00 \[ andrew@pc02 r \]$ ls f0 f1 ``` <a name="long-running-processes"></a> ## Long-Running Processes <a name="yes-nohup-ps-kill"></a> ### `yes / nohup / ps / kill` [[ Back to Table of Contents ]](#toc) Sometimes, `ssh` connections can disconnect due to network or hardware problems. Any processes initialized through that connection will be “hung up” and terminate. Running a command with `nohup` insures that the command will not be hung up if the shell is closed or if the network connection fails. Run `yes` (continually outputs "y" until it’s killed) with `nohup`: ``` \[ andrew@pc01 ~ \]$ nohup 是 & \[1\]13173 ``` `ps` shows a list of the current user’s processes (note PID number 13173): ``` \[ andrew@pc01 ~ \]$ ps | sed -n '/是/p' 13173 分/10 00:00:12 是 ``` _...log out and log back into this shell..._ The process has disappeared from `ps`! ``` \[ andrew@pc01 ~ \]$ ps | sed -n '/是/p' ``` But it still appears in `top` and `htop` output: ``` \[ andrew@pc01 ~ \]$ 頂部 -bn 1 | sed -n '/是/p' 13173 安德魯 20 0 4372 704 636 D 25.0 0.0 0:35.99 是 ``` Kill this process with `-9` followed by its process ID (PID) number: ``` \[ andrew@pc01 ~ \]$ 殺死 -9 13173 ``` It no longer appears in `top`, because it’s been killed: ``` \[ andrew@pc01 ~ \]$ 頂部 -bn 1 | sed -n '/是/p' ``` <a name="cron"></a> ### `cron / crontab / >>` [[ Back to Table of Contents ]](#toc) `cron` provides an easy way of automating regular, scheduled tasks. You can edit your `cron` jobs with `crontab –e` (opens a text editor). Append the line: ``` - - - - - 日期 >> ~/datefile.txt ``` This will run the `date` command every minute, appending (with the `>>` operator) the output to a file: ``` \[ andrew@pc02 ~ \]$ head ~/datefile.txt 2019 年 1 月 12 日星期六 14:37:01 GMT 2019 年 1 月 12 日星期六

如何撰寫出色的 README 文件

可以說,對於任何開源專案來說,最重要的文件就是自述文件。一個好的自述文件不僅告訴人們該專案的用途和用途,還告訴人們他們如何使用該專案並為其做出貢獻。 如果您在撰寫自述文件時沒有充分解釋您的專案的用途或人們如何使用它,那麼它幾乎違背了開源的目的,因為其他開發人員不太可能參與或為其做出貢獻。 TL;DR - 太長?跳到最後並使用我的[模板](#template)。 什麼是自述文件? -------- 本質上,自述文件是一個單一的文字檔案( `.txt`或`.md` ),可作為專案或目錄的一站式文件。對於大多數開源專案來說,它通常是最明顯的文件和登陸頁面。即使自述文件的名稱全部大寫,也是為了吸引讀者的注意力並確保這是他們首先閱讀的內容。 有證據顯示自述文件的歷史可以追溯到 20 世紀 70 年代。我能找到的最古老的例子是 DEC PDP-10 計算機的[自述文件](http://pdp-10.trailing-edge.com/decus_20tap3_198111/01/decus/20-0079/readme.txt.html),日期為 1974 年 11 月 27 日。儘管自述文件名稱的起源存在爭議,但最流行的兩種理論是: 1. 帶有打孔卡的原始大型計算機的程式設計師會留下一疊帶有“READ ME!”的紙質指令。寫在前面。 2. 這個名字是向劉易斯·卡羅爾的《愛麗絲夢遊仙境》致敬,其中主角愛麗絲發現了一瓶標有“喝我”的藥水和標有“吃我”的蛋糕,這使她的體型發生了變化。 自述文件中應包含哪些內容? ------------- 好的,那麼一個很棒的自述文件該包含什麼內容呢?作為起點,我建議您包括以下關鍵內容: **1. 命名事物** 不要忘記為您的專案或功能命名。 GitHub 上有數量驚人的沒有名稱的專案。 **2. 介紹或總結** 寫一篇簡短的兩三行簡介,解釋你的專案的用途和用途。還要省略“簡介”、“摘要”或“概述”等標題 - 很明顯這是一個簡介。 **3. 先決條件** 在介紹之後立即加入一個部分,標題為列出任何想要使用該專案的人在開始之前可能需要的任何先決知識或工具。例如,如果它在最新版本的 Python 上執行,請告訴他們安裝 Python。這是一個例子: ``` Prerequisites Before you continue, ensure you have met the following requirements: * You have installed the latest version of Ruby. * You are using a Linux or Mac OS machine. Windows is not currently supported. * You have a basic understanding of graph theory. ``` **4. 如何安裝** 提供安裝步驟!令人驚訝的是,我遇到的許多專案只提供基本的使用說明,並期望您神奇地知道如何安裝它。如果需要多個步驟,請確保將安裝分解為編號的步驟。 **5. 如何使用該東西** 新增使用者安裝專案後如何使用該專案的步驟。如果您認為有用,請確保包含使用範例和解釋命令選項或標誌的參考。如果您在單獨的文件或網站中有更高級的文件,請從此處連結到該文件。 **6. 如何為事情做出貢獻** 提供為專案做出貢獻的步驟。或者,如果您希望人們在向您的專案貢獻拉取請求之前閱讀它,您可能希望在單獨的文件中建立貢獻者指南,並從自述文件連結到該指南。 **7. 加入貢獻者** 在作者部分感謝為該專案提供幫助的任何貢獻者。這是一種很好的方式,讓開源感覺像是團隊的努力,並感謝每個花時間做出貢獻的人。 **8. 加入致謝** 同樣,如果您使用了其他人的作品(程式碼、設計、圖像等),並且該作品具有需要確認的版權,您可能需要在此處加入。您還可以感謝為該專案提供幫助的任何其他開發商或機構。 **九、聯絡方式** 您可能不想這樣做,因為您是一個非常注重隱私的人,但如果有人有疑問、想要與您合作或對您的專案印象深刻並為您提供工作機會,那麼將您的聯絡方式放在前面是有意義的中心。 **10.新增許可證訊息** 如果適用,您肯定希望包含許可證資訊。除非您提供此軟體,否則依賴第三方軟體的新創公司和其他公司不太可能能夠使用您的專案。請造訪[Choosealicense.com](https://choosealicense.com/)或[opensource.org](https://opensource.org/licenses) ,以取得您可以使用的授權清單。 在您的自述文件中加入耀斑 🔥 -------------- 如果您確實想讓您的自述文件脫穎而出並且看起來具有視覺吸引力,您可以執行以下操作: - **新增徽標**:如果您的專案有徽標,請將其新增至自述文件的頂部。品牌使專案看起來更專業並幫助人們記住它。 - **新增徽章或盾牌**:您可以新增徽章和盾牌以反映專案的當前狀態、它使用的許可證以及它使用的任何依賴項是否是最新的。而且它們看起來很酷!您可以在[Shields.io](https://shields.io/)找到徽章清單或自行設計。 - **新增螢幕截圖**:有時一個簡單的螢幕截圖或一組螢幕截圖可以表達的內容遠遠超過一千個單字。但請注意,如果您確實使用螢幕截圖,則每次更新專案時都需要更新它們。 - **使用表情符號?** :現在很多專案似乎都使用表情符號,儘管是否使用它們取決於您。它們是為你的自述文件注入一點色彩和幽默的好方法,讓專案感覺更人性化。 如果您使用[所有貢獻者](https://allcontributors.org/)來感謝貢獻,您可以使用他們的[表情符號鍵](https://allcontributors.org/docs/en/emoji-key)來表示不同的貢獻類型: ``` * 🐛 for raising a bug ``` ``` * 💻 for submitting code ``` ``` * 📖 for docs contributions etc. ``` 這是 GitHub 徽章或盾牌的樣子,供參考(毫無疑問您以前見過它們!): ![Shields.io 徽章](https://thepracticaldev.s3.amazonaws.com/i/de766ouyuouxmjs2yvcm.png) 我的模板<a name="template"></a> --------------------------- 我建立了一個模板,涵蓋了本文中提出的大部分建議。請隨意分叉存儲庫,提出改進建議或根據自己的目的自訂它!您可以在 GitHub[上](https://github.com/scottydocs/README-template.md)找到我的模板。 資源 -- 如果您需要更多有關自述文件的建議,我還推薦以下資源: - Daniel Beck 在 2016 年 Write the Docs 的演講[「Write the Readable」](https://www.youtube.com/watch?v=2dAK42B7qtw) 。 - Lorna Jane Mitchell 在 API 文件 2019 中的演講[「Github 作為登陸頁面」](https://youtu.be/fXMN4X9B8Rg) 。 - 查看 Franck Abgrall 的[README 產生器](https://github.com/kefranabg/readme-md-generator)。 --- 原文出處:https://dev.to/scottydocs/how-to-write-a-kickass-readme-5af9

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

100 多個帶有原始程式碼的 JavaScript 專案

您是否正在尋找**最好的 JavaScript 專案**來透過原始程式碼增加您的 JavaScript 知識? 在這篇文章中,我分享了 100 個最佳 JavaScript 教學。有各種各樣的專案,例如初學者 JavaScript 專案、中級 JavaScript 專案和高級 JavaScript 專案。 因此,無論您對 JavaScript 有什麼樣的了解,這些專案都會對您有所幫助。 🥳🥳 JavaScript 專案 ------------- JavaScript 是用於 Web 開發的最受歡迎的程式語言之一。它用途廣泛、功能強大,可用於建立各種專案,從簡單的腳本到複雜的 Web 應用程式。 如果您希望提高您的 JavaScript 技能或向潛在雇主展示您的能力,那麼**使用原始程式碼開發 JavaScript 專案**是一個很好的方法。 這裡我給了每個專案的源碼連結。因此,您可以自己練習這些**JavaScript 專案**。 😇 ![成為 JS 專家](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u6gnnsmqtf4irq895e0s.jpg) 最佳 JavaScript 專案創意 ------------------ 讓我們來看看前 100 個 JavaScript 專案並討論如何建立它們。 ### 適合初學者的 JavaScript 專案 如果您是一位想要深入編碼世界或尋求擴展技能的初學者,那麼從**簡單的 JavaScript 專案**開始可能是寓教於樂的絕佳方式。這個初學者級 JavaScript 專案一定會對您有幫助。 #### 圖像顏色選擇器 Javascript ![圖像顏色選擇器 Javascript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zswnpz4eqwkbyzlvxsm0.jpg) JavaScript 中的圖像顏色選擇器是一個**簡單的 JavaScript 專案**,可讓使用者直接從圖像中選擇顏色。 它使用戶能夠以互動方式從網頁上顯示的圖像中選取顏色,從而簡化諸如顏色匹配、顏色採樣或從圖像中提取顏色資訊等任務。 [預覽和程式碼](https://codingartistweb.com/2022/11/image-color-picker-javascript/) #### 數字時鐘 JavaScript ![數字時鐘 JavaScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u9ychtonhcv3ccallsze.jpg) JavaScript 中的數位時鐘是一個基於 Web 的應用程式或 JavaScript 專案,它以數位格式在網頁上顯示當前時間。 這是一個常見且簡單的專案,展示如何使用 JavaScript 在網路上建立動態和互動式內容。 [預覽和程式碼](https://dev.to/nehasoni__/digital-clock-using-javascript-2648) #### 使用 JavaScript 的秒錶 ![使用 JavaScript 的秒錶](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3qac5fgivbu54ee4ngy7.jpg) 使用 JavaScript 的秒錶是一個基本的 JavaScript 專案,可讓使用者測量經過的時間。它通常由一個用於開始計時的開始按鈕、一個用於暫停計時器的停止按鈕以及一個用於清除已用時間並重新開始的重置按鈕組成。 [預覽和程式碼](https://dev.to/shantanu_jana/create-a-simple-stopwatch-using-javascript-3eoo) #### RGB 顏色滑桿 JavaScript ![RGB 顏色滑桿 JavaScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6pvy2tq5yz6owpj1jqgj.jpg) JavaScript 中的 RGB 顏色滑桿是一個**適合初學者的完美 JavaScript 專案**,它允許使用者透過調整顏色的紅色、綠色和藍色 (RGB) 分量的值來選擇顏色。 此互動式元件通常由三個滑桿或輸入欄位(每個顏色通道一個)以及一個預覽區域組成,該區域根據所選 RGB 值顯示結果顏色。 [預覽和程式碼](https://codingartistweb.com/2023/05/rgb-color-slider-javascript/) #### JavaScript 年齡計算器 ![JavaScript 年齡計算器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g8nuylom621dansflni0.jpg) JavaScript 年齡計算器是適合初學者的簡單 JavaScript 專案,它根據出生日期和當前日期計算一個人的年齡。它通常以生日的形式獲取用戶的輸入,然後計算並顯示他們的年齡。 [預覽和程式碼](https://dev.to/code_mystery/javascript-age-calculator-calculate-age-from-date-of-birth-o9b) #### 懸停時影像縮放 ![懸停時影像縮放](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/llrsmmgwkwjo0feoslk5.jpg) JavaScript 中的懸停圖像縮放功能可讓使用者將遊標懸停在圖像上時放大圖像。 此效果可讓使用者更仔細地查看圖像中的細節,從而增強使用者體驗,而無需使用者點擊其他控製或與其他控制項進行互動。 [預覽和程式碼](https://dev.to/shantanu_jana/image-zoom-on-hover-using-javascript-code-demo-328g) #### OTP 生成器 JavaScript ![OTP 生成器 JavaScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ad6rb29svfif5b0zg39j.jpg) JavaScript 中的 OTP(一次性密碼)產生器是一種產生唯一程式碼的工具,該程式碼通常由數字或字母數字字元組成,該程式碼一次性使用或在有限時間內有效。 OTP 通常用於 Web 應用程式中的使用者驗證、雙重認證 (2FA) 和帳戶驗證流程。 [預覽和程式碼](https://codingartistweb.com/2023/12/otp-generator/) #### JavaScript 手電筒效果 ![JavaScript 手電筒效果](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4gyd41fpahtqfvc860h9.jpg) JavaScript 手電筒效果模擬手電筒或聚光燈在網頁上產生的照明。它是一種互動式視覺效果,透過將注意力集中在頁面的特定元素或區域來增強使用者體驗。 實現手電筒效果通常涉及在網頁上建立遮罩層,並允許使用者使用滑鼠或觸控輸入來移動手電筒。 [預覽和程式碼](https://groundtutorial.com/flashlight-effect-with-html-css-javascript/) #### 影像手風琴 ![影像手風琴](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ziojqmkvy1lbnzf1u7gx.jpg) JavaScript 中的圖像手風琴是一種使用者介面元素,它以垂直或水平堆疊的形式顯示一組圖像,允許用戶展開和折疊單個圖像以顯示與每個圖像相關的更多細節或資訊。 這種互動創造了一種視覺上吸引人的方式來呈現圖像集合,同時節省網頁空間。 [預覽和程式碼](https://groundtutorial.com/image-accordion-using-html-css-javascript/) #### 拖放元素 ![拖放元素](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iohtqrsk79qw7lva8ngx.jpg) JavaScript 拖放功能可讓使用者透過點擊網頁元素並將其拖曳到頁面上的不同位置來與它們互動。 此功能通常在 Web 應用程式中用於執行諸如重新排序清單、在容器之間移動元素或建立互動式使用者介面等任務。 [預覽和程式碼](https://groundtutorial.com/draggable-element-javascript/) #### 隨機數產生器 ![隨機數產生器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mpezbhvuioe4hpd87yly.jpg) JavaScript 中的隨機數產生器(RNG)是一種產生指定範圍內或具有特定特徵的隨機數的工具。隨機數通常用於遊戲、模擬、密碼學和統計分析等應用。 JavaScript提供了用於生成隨機數的內建函數和方法,可以根據應用程式的要求進行自訂。 [預覽和程式碼](https://foolishdeveloper.com/random-password-generator-with-javascript/) #### 使用 JavaScript 的小費計算器 ![使用 HTML、CSS 的小費計算器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7mcqubvfib3v63y5vhlu.jpg) [預覽和程式碼](https://groundtutorial.com/tip-calculator-html-css-javascript/) #### HTML、CSS、JS 中的雙範圍滑桿 ![HTML、CSS 中的雙範圍滑桿](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w6knk161ja08o9t3bsh3.jpg) [預覽和程式碼](https://groundtutorial.com/double-range-slider-in-html-css-javascript/) #### 使用 JavaScript 的倒數計時器 ![使用 JavaScript 的倒數計時器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wdi6x6fqxrv8q0o4acs3.jpg) [預覽和程式碼](https://dev.to/shantanu_jana/how-to-build-a-countdown-timer-using-javascript-4f4h) #### 使用 JavaScript 的漸層顏色產生器 ![使用 JavaScript 的漸層顏色產生器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pocfjwy56br7v0zg03kn.jpg) [預覽和程式碼](https://dev.to/shantanu_jana/gradient-color-generator-with-javascript-html-5e3p) #### 使用 Javascript 懸停時圖像縮放 ![使用 Javascript 懸停時圖像縮放](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p50dvkjpswitvvoglt26.jpg) [預覽和程式碼](https://dev.to/shantanu_jana/image-zoom-on-hover-using-javascript-code-demo-328g) ### 中階 JavaScript 專案 對於中級 JavaScript 開發人員來說,有許多專案提供了擴展技能、探索新技術和深入研究 Web 開發概念的機會。以下是為中級開發人員量身定制的 JavaScript 專案想法清單: #### 自訂遊標 ![自訂遊標](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3hg920h1fv61et73v6na.jpg) JavaScript 中的自訂遊標是指以自訂設計的圖形或 HTML 元素取代預設遊標外觀(例如箭頭或手形指標)的能力。這使得網頁開發人員能夠建立與網站主題或品牌相符的獨特且具有視覺吸引力的遊標效果。 [預覽和程式碼](https://foolishdeveloper.com/simple-mouse-cursor-effects-using-javascript-free-code/) #### 回文檢查器應用程式 ![回文檢查器應用程式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eioy07s621eqjc1e5fi5.jpg) JavaScript 中的回文檢查器應用程式是一個簡單的 Web 應用程式,允許使用者輸入一串字元並檢查它是否是回文。 回文是單字、片語、數字或其他字元序列,無論空格、標點符號和大小寫,向前和向後讀起來都相同。 [預覽和程式碼](https://groundtutorial.com/how-to-check-palindrome-in-javascript/) #### 滑動圖像拼圖 Javascript ![滑動圖像拼圖 Javascript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t3gn4vl9mvapb5b3cvot.jpg) JavaScript 中的滑動圖像拼圖是一種經典遊戲,其中圖像被分成較小的圖塊,玩家的目標是透過滑動它們來重新排列圖塊以形成原始圖像。遊戲提供了娛樂性和挑戰性的體驗,同時也考驗玩家解決問題的能力和空間推理能力。 [預覽和程式碼](https://groundtutorial.com/image-puzzle-game-javascript/) #### 使用 Javascript 的貨幣轉換器 ![使用 Javascript 的貨幣轉換器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/41ncmzvsq5pj9a6vbjbn.jpg) 使用 JavaScript 的貨幣轉換器是一個 Web 應用程式,允許用戶根據當前匯率將價值從一種貨幣轉換為另一種貨幣。 用戶通常輸入他們想要轉換的金額,選擇來源貨幣,然後選擇目標貨幣。然後,應用程式從 API 檢索最新的匯率並相應地計算換算後的金額。 [預覽和程式碼](https://codingartistweb.com/2023/03/currency-converter-with-javascript/) #### 猜顏色遊戲Javascript ![猜顏色遊戲Javascript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wp4a678c6zsw05ttmd9i.jpg) JavaScript 中的顏色猜測遊戲是一種互動式 Web 應用程式,玩家會看到目標顏色,並且必須猜測該顏色的 RGB 或十六進位程式碼。遊戲通常會提供線索來幫助玩家做出有根據的猜測,例如在正方形中顯示顏色或提供有關顏色成分(紅色、綠色、藍色)或亮度的提示。 [預覽和程式碼](https://groundtutorial.com/color-guessing-game-javascript/) #### 拖放可排序列表 ![拖放可排序列表](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fgyicbi03b7fac9cje89.jpg) JavaScript 中的拖放可排序清單是一個使用者介面元件,可讓使用者透過將清單中的專案拖曳到新位置來重新排序。 此功能通常在 Web 應用程式中用於執行諸如重新排列待辦事項清單中的專案、對圖庫中的圖像進行排序或在文件管理器中組織文件等任務。 [預覽和程式碼](https://codingartistweb.com/2023/02/drag-and-drop-sortable-list-javascript/) #### 觸碰並拖曳影像滑桿 ![觸碰並拖曳影像滑桿](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s4idy4zthbl0v6wv4nf6.jpg) JavaScript 中的觸控和拖曳圖像滑桿是一個使用者介面元件,可讓使用者水平滑動或拖曳圖像以在圖像庫中導航。這種類型的滑桿針對智慧型手機和平板電腦等支援觸控的裝置進行了最佳化,但也可以與桌面瀏覽器上基於滑鼠的互動無縫協作。 [預覽和程式碼](https://groundtutorial.com/touch-image-slider-using-html-css-javascript/) #### 偵測網路速度 JavaScript ![偵測網路速度 JavaScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/twmtmhtmia47dzd9mjr5.jpg) 在 JavaScript 中偵測網路速度涉及測量從伺服器下載已知大小的檔案所需的時間。有多種技術可以實現此目的,包括使用 XMLHttpRequest、fetch API 或 HTML5 功能(例如網路資訊 API)。 [預覽和程式碼](https://foolishdeveloper.com/detect-internet-speed-javascript/) #### JavaScript 模因應用程式 ![JavaScript 模因應用程式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j2q1nbc4ckpwemkok3hx.jpg) JavaScript Memes 應用程式是一個 Web 應用程式,允許使用者瀏覽、搜尋和查看 memes。它通常從 API 或資料庫中獲取模因,並將其顯示在用戶友好的介面中,通常具有分頁、排序、過濾和社交共享選項等功能。用戶可以與迷因互動,例如喜歡或分享它們,並且可以上傳自己的迷因。 [預覽和程式碼](https://codingartistweb.com/2022/10/memes-app-html-css-javascript/) #### 多個骰子滾軸 ![多個骰子滾軸](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tmfp7t045awkyniij91a.jpg) JavaScript 中的多個骰子滾輪是一個允許使用者滾動多個不同類型的骰子(例如,d4、d6、d8、d10、d12、d20)並顯示結果的工具。 它通常用於《龍與地下城》等桌上角色扮演遊戲 (RPG) 中,或用於各種遊戲或教育目的。 [預覽和程式碼](https://codingartistweb.com/2023/10/multiple-dice-roller/) #### 密碼強度背景 ![密碼強度背景](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8hkeyw0wr9bc3ajry59f.jpg) JavaScript 中的密碼強度背景是一項功能,當使用者在輸入欄位中鍵入密碼時,可以提供使用者有關密碼強度的視覺回饋。 此回饋通常是透過更改輸入欄位的背景顏色來提供的,以根據預先定義的標準指示密碼是弱、中等還是強。 [預覽和程式碼](https://codingartistweb.com/2023/10/password-strength-background/) #### 自訂滑鼠懸停效果 ![自訂滑鼠懸停效果](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lm53lriqk83p9qbaa8eg.jpg) JavaScript 中的自訂滑鼠懸停效果是一種視覺效果,當使用者將滑鼠懸停在網頁上的元素上時,效果會變更該元素的外觀或行為。 這種效果可以透過使用 CSS 過渡或動畫結合 JavaScript 事件監聽器來偵測滑鼠懸停事件並觸發所需的效果來實現。 [預覽和程式碼](https://codingartistweb.com/2023/12/custom-mouse-hover-effect-with-javascript/) #### 文字相似度檢查器 ![文字相似度檢查器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g4m8phfjm38cc0uug7tf.jpg) JavaScript 中的文字相似度檢查器是一種測量兩段文字或文件之間相似性的工具或應用程式。 文字相似度可以使用各種演算法和技術來計算,例如餘弦相似度、Jaccard 相似度、Levenshtein 距離或 TF-IDF(詞頻-逆文件頻率)。 [預覽和程式碼](https://codingartistweb.com/2023/09/text-similarity-checker/) #### 使用 JavaScript 的拋硬幣遊戲 ![使用 JavaScript 的拋硬幣遊戲](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gtd74ui4i8ds0q6k3b6o.jpg) [預覽和程式碼](https://dev.to/shantanu_jana/coin-toss-game-using-javascript-css-1cf0) #### Javascript 剪刀石頭布遊戲 ![Javascript 剪刀石頭布遊戲](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/if9zccyex7o9n0sfgpt7.jpg) [預覽和程式碼](https://groundtutorial.com/rock-paper-scissor-game-javascript/) #### JavaScript 中的右鍵上下文選單 ![JavaScript 中的右鍵上下文選單](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ope2hkppwntnhnrgskf9.jpg) [預覽和程式碼](https://dev.to/shantanu_jana/custom-right-click-context-menu-in-javascript-4112) ### 高級 JavaScript 專案 高階 JavaScript 專案通常涉及建立複雜的 Web 應用程式或利用複雜框架、程式庫和 API 的軟體解決方案。 這些專案可能需要前端開發、後端開發或全端開發的專業知識。以下是高級 JavaScript 專案的一些範例: #### 帶有儲存的隨機報價產生器 ![帶有儲存的隨機報價產生器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/duvtugkuougrls6ylu6b.jpg) JavaScript 中帶有儲存功能的隨機報價產生器是一個 Web 應用程式,它向用戶顯示隨機報價,並允許他們保存自己喜歡的報價以供以後查看。 該應用程式通常從預先定義清單或外部 API 檢索報價,在網頁上動態顯示它們,並為使用者提供使用 localStorage 儲存和檢索所選報價的選項。 [預覽和程式碼](https://dev.to/nehasoni__/random-quote-generator-using-html-css-and-javascript-3gbp) #### 使用 JavaScript 的螢幕截圖應用程式 ![使用 JavaScript 的螢幕截圖應用程式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8d0edi0hwddzum4k78ux.jpg) 使用 JavaScript 建立螢幕截圖擷取應用程式涉及利用瀏覽器功能來擷取目前網頁或頁面中特定元素的螢幕截圖。 雖然 JavaScript 本身無法直接截取螢幕截圖,但它可以與瀏覽器 API 互動以觸發螢幕截圖擷取功能。 [預覽和程式碼](https://codingartistweb.com/2023/05/screenshot-capture-app-using-javascript/) #### 警報應用程式 JavaScript ![警報應用程式 JavaScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bwr8w5254xt70mzcmtvi.jpg) JavaScript 中的鬧鐘應用程式是一個簡單的應用程式,可讓用戶設定鬧鐘並在特定時間接收通知或警報。 它通常涉及用戶互動來設定所需的鬧鐘時間,然後應用程式在背景執行,在達到設定時間時觸發通知。 [預覽和程式碼](https://www.codingnepalweb.com/simple-alarm-clock-html-javascript/) #### 文字轉語音轉換器 ![文字轉語音轉換器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ogf39oucpxjiof9uipjt.jpg) JavaScript 中的文字轉語音 (TTS) 轉換器是一種將書面文字轉換為口語單字的工具或應用程式。它利用瀏覽器 API 或第三方庫將文字合成為語音,並透過裝置的揚聲器或耳機播放。以下是使用 HTML、CSS 和 JavaScript 的文字轉語音轉換器的基本實作: [預覽和程式碼](https://dev.to/shantanu_jana/text-to-speech-converter-with-javascript-30oo) #### QR 碼產生器 JavaScript ![QR 碼產生器 JavaScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m0vcmr2mqoy700z80fcc.jpg) JavaScript 中的 QR 程式碼產生器是一種允許使用者在 Web 應用程式中動態建立快速回應 (QR) 程式碼的工具。 QR 碼是二維條碼,可以包含各種類型的訊息,例如 URL、文字、聯絡資訊或 Wi-Fi 憑證。 [預覽和程式碼](https://dev.to/murtuzaalisurti/how-to-make-a-qr-code-generator-using-vanilla-javascript-3cla) #### 測驗應用程式 JavaScript ![測驗應用程式 JavaScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aj3aaque8i3myerfuvtn.jpg) JavaScript 中的測驗應用程式是一個互動式 Web 應用程式,它向使用者提出一系列問題並允許他們選擇答案。回答完所有問題後,應用程式會評估答案並提供回饋,例如總分和正確答案。 [預覽和程式碼](https://codingartistweb.com/2022/06/quiz-app-with-javascript/) #### 使用 Javascript 的天氣應用程式 ![使用 Javascript 的天氣應用程式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u3wiz08coy82gig4xe6r.jpg) 使用 JavaScript 的天氣應用程式是一個 Web 應用程式,可為使用者提供特定位置的當前天氣資訊。它通常從天氣 API 檢索天氣資料、處理資料並將其顯示在使用者友好的介面中。 [預覽和程式碼](https://codingartistweb.com/2022/07/weather-app-with-javascript/) #### 自訂視訊播放器 ![自訂視訊播放器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xspo2vpcru8kjvpz6wye.jpg) JavaScript 中的自訂影片播放器是一個 Web JavaScript 專案,它提供用於播放影片內容的自訂使用者介面 (UI)。它通常包括播放、暫停、音量控制、播放速度調整、進度條、全螢幕模式和自訂樣式等功能。 [預覽和程式碼](https://codingartistweb.com/2022/07/custom-video-player-using-javascript/) #### 學生 JavaScript 專案 如果您是學生,那麼這些 JavaScript 專案將對您有很大幫助。 JavaScript 提供了適合不同技能水平的學生(從初學者到高級學習者)的各種專案。 這些專案不僅有助於強化基本概念,也提供 Web 開發的實務經驗。以下是一些**供學生使用的 javascript 專案想法**。 #### 星級評級 JavaScript ![星級評級 JavaScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rm8udkic9kz59e4t528b.jpg) JavaScript 中的星級評級元件是一個學生導向的 JavaScript 專案,可讓使用者透過選擇代表不同滿意度或品質等級的星級來對專案進行評級。通常,它由一組水平排列的可點擊星形圖示組成,其中選定的星形突出顯示以指示使用者的評級。 [預覽和程式碼](https://dev.to/codingnepal/star-rating-system-in-html-css-javascript-97a) #### 五彩紙屑效果 Javascript ![五彩紙屑效果 Javascript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rd6ph3ag1fb4rfnrcgrl.jpg) JavaScript 中的五彩紙屑效果是指一種圖形效果,其中彩色「五彩紙屑」(小紙片或其他材料)在螢幕上散佈或投擲,通常以節日或慶祝的方式進行。 [預覽和程式碼](https://codingartistweb.com/2022/11/confetti-effect-javascript/) #### 刮刮卡Javascript ![刮刮卡Javascript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fsaou1alqoca7ks3swe8.jpg) JavaScript 中的刮刮卡是一個**最好的 js 專案**,它模仿刮掉隱藏區域以顯示下面內容的體驗,類似於彩票或促銷卡。在 Web 開發中,這種效果通常使用 HTML5 畫布元素和 JavaScript 來處理互動來實作。 [預覽和程式碼](https://codingartistweb.com/2022/08/scratch-card-with-javascript/) #### 用 Javascript 進行西蒙遊戲 ![用 Javascript 進行西蒙遊戲](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ob7ng3dcqnvhpbv5z7u2.jpg) 西蒙遊戲是一款經典的記憶技巧電子遊戲。它涉及一個播放一系列音調和燈光的設備,然後玩家必須重複該序列。 在 Simon 遊戲的 JavaScript 實作中,您通常會建立一個使用者介面,其中的按鈕代表每種顏色,遊戲邏輯將涉及產生和顯示一系列顏色供玩家模仿。 [預覽和程式碼](https://dev.to/nanythery/coding-my-first-game-with-javascript-simon-says-60d) #### 自訂音樂播放器 Javascript ![自訂音樂播放器 Javascript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yoexh51at6t9gbau64rb.jpg) 使用 JavaScript 建立自訂音樂播放器涉及建立允許使用者控制音訊播放的使用者介面。[預覽和程式碼](https://dev.to/codingnepal/create-custom-music-player-in-javascript-2367) #### 富文本編輯器 ![富文本編輯器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q7ajobdoysmcm3a8mok0.jpg) 富文本編輯器是一個元件,使用戶能夠使用類似於文字處理器的各種樣式和格式選項來編輯和格式化文字。這些編輯器通常提供粗體、斜體、底線、文字對齊、專案符號、編號清單等功能。 [預覽和程式碼](https://codingartistweb.com/2022/04/rich-text-editor-with-javascript/) > 如果您喜歡這些最佳 JavaScript 專案,那麼我將向此列表加入更多專案。請不要忘記喜歡分享和關注。 使用可用原始碼開始**JavaScript 專案**是增強程式設計技能和擴展知識的絕佳方法。透過剖析現有專案,您可以學習其他人的程式碼,了解不同的設計模式,並發現針對常見挑戰的創新解決方案。😊😊 希望您喜歡這些 JavaScript 專案。您將在我給出的源程式碼連結中獲得逐步說明。希望最佳 JavaScript 專案創意能幫助您增加 JavaScript 知識。 ![專案](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/urerlcgx7v4wkjxqvtmk.jpg) 因此,捲起袖子,深入研究原始碼,開始建立一些令人驚奇的東西! 🥳🥳 --- 原文出處:https://dev.to/shantanu_jana/100-javascript-projects-with-source-code-59lo

關於 GIT 你需要了解的一切

我相信您可以想像版本控製程式碼的重要性,以便我們可以**恢復變更**並**恢復遺失的資料以及其他可能性**。 我打賭你知道有人*(不是我呵呵)*通過使用越來越有創意的名稱建立文件副本來對其文件進行版本控制... ![GIF 模擬具有不同名稱的檔案的複製。範例:文章、文章最終版本等。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sffhjyl41pfnjklivnsv.gif) 在 1972 年之前,隨著**SCCS *(原始碼控制系統)***的發布,這是有史以來第一個**集中式**版本控制軟體之一,這可能是任何人對其程式碼進行版本控制的方式。 但我們在這裡不是在談論 SCCS,我們現在真正感興趣的是**GIT** ,這是一款**分散式**開源版本控制軟體,明年*(07/04/2005)*將慶祝其誕生 20 週年。 目錄 -- - [1.GIT是什麼?](#chapter-1) - [2.GIT如何運作?](#chapter-2) - [3.安裝GIT](#chapter-3) - [4.配置GIT](#chapter-4) - [5. 啟動本機儲存庫](#chapter-5) - [6. 使用 GIT](#chapter-6) - [7. 認識分支](#chapter-7) - [8. 與遠端倉庫同步](#chapter-8) - [9. 結論](#chapter-9) - [10. 參考文獻](#chapter-10) 1.GIT是什麼?<a name="chapter-1"></a> --------------------------------- GIT 是一個開源**分散式**版本控制系統,於 2005 年推出,由 Linus Torvald *(Linux 核心建立者)*開發。 使用GIT,我們可以在本地**控制專案的版本***(在工作資料夾中)*並將所有變更同步到遠端儲存庫*(例如在GitHub上)* 。 2.GIT如何運作?<a name="chapter-2"></a> ---------------------------------- 想像一個**實體**文件櫃,其中有一個包含所有專案文件的資料夾。每當有人需要操作文件時,他們都必須將其拾取,**將其從資料夾中刪除,並在完成後將其返回到資料夾中**。因此,兩個人**不可能**處理同一個文件,完全避免了任何可能的衝突。 **但這不是 Git 的工作原理!** *(感謝上帝)* 這就是**集中式**版本控制系統的工作方式,其中使用者需要**「簽出」**和**「簽入」**文件,即每當有人需要處理特定文件時,他們需要簽出該文件,**刪除從儲存庫中獲取**文件,然後在工作完成後簽入該文件,**並將其返回儲存庫**。 ![GIF 模擬集中式版本控制系統的操作。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/26a9j0m4pcu5prb0kauo.gif) 在像**GIT**這樣的**分散式**系統中,多個人可以存取同一個遠端儲存庫中的檔案。每當有人需要操作文件時,他們只需將其**克隆***(或克隆整個存儲庫)*到本地計算機,然後將修改發送回遠端存儲庫。這使得**多人可以處理同一個專案**,甚至操作**相同的文件**。 ![GIF 模擬分散式版本控制系統的操作。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nb0x0u9kc6m7z2hz7zfj.gif) 這就是允許大型**開源**專案的分佈,來自世界不同地區的人們在同一個專案上工作,管理修改和可能的衝突*(是的,這裡可能會發生合併衝突)* 。 3.安裝GIT<a name="chapter-3"></a> ------------------------------- **GIT**適用於主要作業系統*(Windows、Linux、MacOs...),*安裝過程非常簡單,可以透過**命令列**或透過[git-scm.com](https://git-scm.com/)的**官方安裝程式**完成。 ### 3.1 在 Windows 上 要在 Windows 上安裝 GIT,只需存取官方網站並[下載安裝程式即可](https://git-scm.com/download/win)。然後只需**按照說明進行操作**,一切都會好起來,然後我們就可以在終端機中使用 GIT 命令了。 ### 3.2 在Linux上 對於Linux,我們可以使用以下**命令**安裝**GIT** : ``` sudo apt install git-all ``` 透過這樣做, **GIT**必須準備好在我們的終端中運作。 ### 3.3 在 MacOS 上 對於 Mac,安裝**GIT**最簡單的方法是安裝[Homebrew](https://brew.sh/) ,然後在終端機中執行以下**命令**: ``` brew install git ``` 然後**GIT**必須準備好在我們的終端中運作。 4.配置GIT<a name="chapter-4"></a> ------------------------------- 安裝後,使用以下**命令設定 GIT**很重要: ``` git config --global user.name "[username]" # e.g. John Doe ``` ``` git config --global user. email "[[email protected]]" # e.g. [email protected] ``` > 此外,也可以透過刪除`--global`標籤來為某些本機儲存庫配置特定使用者。 5. 啟動本機儲存庫<a name="chapter-5"></a> ---------------------------------- 配置**GIT**後,我們就可以**啟動本地儲存庫了**。為此,我們可以**從頭開始一個新的儲存庫**或**複製現有的遠端儲存庫**。 ### 5.1 從頭開始(git init) 要啟動新儲存庫,只需導航到所需的儲存庫**根資料夾**並執行以下命令: ``` git init ``` ![Linux 終端機執行「git init」命令並顯示結果的螢幕截圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iw35xe9jwrwzo937to5b.png) 透過這樣做,將在專案資料夾內建立一個`.git`目錄,該目錄將**負責此本機儲存庫的工作資料夾中的版本控制**。 ### 5.2 克隆現有儲存庫(git clone) 克隆現有遠端儲存庫就像從頭開始建立新儲存庫一樣簡單。為此,只需使用`git clone`命令,將要複製**的儲存庫的 URL**作為參數傳遞到要複製儲存庫的資料夾中: 複製現有的遠端儲存庫就像從頭開始建立新的儲存庫一樣簡單。為此,只需使用`git clone`命令,將**遠端儲存庫 URL**克隆到我們要下載儲存庫的資料夾中: ``` git clone [repository-url] ``` ![Linux 終端機執行「git clone」命令並顯示結果的螢幕截圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nlt8rtua4ri7kpnna5el.png) 然後整個存儲庫必須**克隆**到我們的本地機器並**自動連結到相關的遠端存儲庫**。 > 有了複製的儲存庫,我們以後就不再需要使用`git remote`指令了。 6. 使用 GIT<a name="chapter-6"></a> --------------------------------- 在我們的**本機儲存庫**中,我們可以建立專案所需的文件,但它們**不會由 GIT 自動同步**,當有任何變更需要版本控制時,我們需要報告它。 因此,我們可以根據需要**操作**文件,並**在完成所需的變更後**,**將更新的文件傳送到 GIT** 。 為此,重要的是要了解版本控制中有**3 個階段的無限流***(是的,無限)* : ``` MODIFY -> STAGE -> COMMIT ``` - **修改:**版本控制的第一階段,我們在這裡找到與上一個可用版本相比**已更改的檔案**。 - **STAGE:**版本控制的第二階段,這是我們放置**要新增到下次提交的修改檔案**的地方。 - **COMMIT:**版本控制的最後階段,當我們**確認變更**時,將階段中修改的檔案傳送到本機儲存庫。 提交修改後的文件後,我們在本地存儲庫中有一個可用的**新版本**,它可以再次接收更新,再次*“修改”* ,然後放入*“階段”* ,並再次*“提交”* ,確認較新的版本版本等等*(因此,「無限」哈哈)* 。 > 值得注意的是,提交不會覆蓋已修改文件的舊版本,而是包含新版本以及指向最後版本的指針,從而追蹤 GIT 追蹤的每個文件的版本。 ### 6.1 新增和提交(git add 和 git commit) 儘管聽起來很複雜,但執行版本控制流程**非常簡單**。由於所需的修改已完成,我們使用以下命令**新增要在舞台上提交的修改後的檔案**: ``` git add [filename] ``` > `git add -A` -> 將所有修改的檔案立即加入階段。 > > `git add *.[extensão-do-arquivo]` -> 將所有具有指定檔案副檔名的已修改檔案一次新增至暫存區(例如`git add *.html` ) 我們可以隨時使用`git status`指令檢查目前本機儲存庫**狀態**: ![Linux 終端機執行「git status」命令並顯示結果的螢幕截圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e28lg7wym8s0woytgzqz.png) 請注意,當我們**在建立新檔案後**在儲存庫中執行`git status`時,新檔案將顯示為*「Untracked」* 。這意味著該文件是**全新的**,仍然需要加入到任何提交中才能被**GIT追蹤**。 > 可以讓 GIT 忽略儲存庫中的特定檔案或資料夾。為此,我們只需將一個名為`.gitignore`的檔案新增到根資料夾中,並在其中寫入應忽略的檔案或資料夾的名稱。 > > 注意:被忽略的檔案和資料夾將不再出現在 GIT 軌道上,甚至不會顯示為「未追蹤」。要重置跟踪,只需從`.gitignore`文件中刪除所需的名稱即可。 要包含文件,我們可以使用要新增的文件的名稱來執行`git add`命令*(在本例中為「index.html」)* : ![Linux 終端機的螢幕截圖,執行命令“git add”,然後執行“git status”,顯示結果。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pz1hnk9gpnxtv2s8xort.png) 這樣,透過重新執行`git status`我們可以看到新檔案已新增至*「stage」* ,並**最終準備好在下一次提交中發送**,這可以使用以下命令完成: ``` git commit -m "[descriptive-message]" ``` > 提交具有唯一的 ID(雜湊碼)並且是**IMMUTABLE 的**,即一旦確認就無法修改。 > > `git commit -a` -> 執行直接提交,將所有修改的檔案新增至暫存區並提交它們。 **成功提交檔案後**,執行`git status`時,我們注意到**沒有更多修改的檔案需要上傳**,因為所有修改都已在上次**提交**時有效保存在我們的本機儲存庫中。 ![Linux 終端機的螢幕截圖,執行指令“git commit”,然後執行“git status”,顯示結果。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ryqqs4mi46hxtuex199i.png) 此外,還可以使用`git log`指令查看儲存庫的提交日誌來**驗證所做的更改**,該指令顯示所有提交的一些元資料,例如雜湊碼、分支、作者、日期等。 ![Linux 終端機執行命令「git log」並顯示結果的螢幕截圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ljvj9se6srxslsu8vsj7.png) 可以重複整個過程來加入我們專案所需的新文件,修改它們並透過進行新的提交將它們發送到本地儲存庫。 ![GIF 模擬 GIT 分支中的多次提交。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2uez3henix8kchperuw8.gif) > `git log -N` -> 顯示最近 N 次提交的日誌。 > > `git log [branch-A] [branch-B]` -> 顯示「branch-B」中但不在「branch-A」中的提交日誌。 > > `git log --follow [filename]` -> 顯示更改指定檔案的提交日誌,即使它已更改名稱。 > > `git diff` -> 列出與儲存庫中最新可用版本相比所做的變更。 > > `git diff [nome-do-arquivo]` -> 列出對指定檔案相對於儲存庫中最後一個可用版本所做的變更。 ### 6.2 撤銷提交前後的更改 **在提交之前**,對本地存儲庫所做的任何更改都可以撤消或更改,但**一旦提交,就無法更改**。這是因為提交是**不可變的物件**,這意味著不可能編輯或更改提交中的資料。 但是,**可以進行新的提交**來撤銷更改,或更正先前提交中的不正確資訊。無論哪種方式,我們都可以使用以下命令之一: ``` git checkout -- [filename] # Discards changes made to the local file before the commit (irreversible action) ``` ``` git reset --hard HEAD # Discards changes made to a file that is in stage (before the commit) ``` ``` git reset --hard HEAD~1 # Discards the last commit made in the local repository (only the last commit) ``` ``` git commit --amend # Creates a new commit, replacing the last commit made in the local repository ``` ``` git revert [commit-hash] # Creates a new commit, reverting the changes of the specified commit ``` 7. 認識分支<a name="chapter-7"></a> ------------------------------- **分支**只不過是儲存庫的一個**分支**,到目前為止,所有操作都已在分支`master/main'`上執行。 > 預設情況下,儲存庫中建立的第一個分支是`master/main` ,它是儲存庫的主分支。 ### 7.1 為什麼要使用分支? 乍看之下似乎沒什麼,但**分店卻為專案的發展賦予了巨大的力量**。 想像一下,我們正在開發一個 Web 平台,並且想要**測試一項新功能**,但我們的儲存庫已經**託管或與其他人共享**,任何有問題的更改都可能會給他們帶來糟糕的體驗。我們可以做什麼? 如果您一直在考慮**複製並貼上**專案資料夾,建立一個新的**「測試版本」** ,那麼您是對的!嗯,差不多… 透過 GIT,我們可以對分支做類似的事情。由於它們是**分支**,我們可以簡單地**建立一個名為「test」的新分支**,從而在完全**隔離的分支**中擁有我們專案的一個版本,準備好進行翻轉,**而不會危及主分支**。 ![GIF 模擬使用新提交建立新分支。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/szc081nndoi18vklty5r.gif) ### 7.2 建立分支(git分支) 建立**分支**意味著建立可以獨立工作的儲存庫的並行副本,而不會影響`master/main`分支。為此,我們只需執行以下命令: ``` git branch [branch-name] ``` > 在沒有特定分支名稱的情況下執行`git branch`指令必須顯示儲存庫中可用分支的列表,並用「\*」標記目前正在使用的分支。 在執行`git branch test`指令之前, `git branch`指令只會傳回`master`分支。 ![Linux 終端機執行「gitbranch」命令、建立新分支並顯示結果的螢幕截圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vqpdrtvhze9qhr31ewbh.png) 建立新分支後,我們可以執行以下命令在可用分支之間切換: ``` git checkout [branch-name] ``` 執行`git checkout test`指令後,我們可以看到**活動分支已切換**。從那一刻起,**所有提交的資訊都會傳送到儲存庫的`test`分支**,而不會影響分支`master/main` 。 ![Linux 終端機執行「git checkout」命令、切換活動分支並顯示結果的螢幕截圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/egau7y81leig8za36myi.png) > 可以根據需要建立任意數量的分支,並且我們可以使用以下命令與現有分支進行互動: > > `git checkout -b [branch-name]` -> 使用給定名稱建立一個新分支並直接切換到它。 > > `git branch -d [branch-name]` -> 刪除指定分支。 > > `git branch -m [new-name]` -> 將目前分支的名稱變更為給定名稱。 ### 7.3 合併分支(git merge) **當完成不同分支**上的工作,並且我們確定所做的更改不會在專案中引起任何問題時,我們可以將當前分支**合併**到`master/main`分支中,**應用當前分支中的所有更改分支到儲存庫的主分支**。 要**合併**分支,我們需要**切換到將接收更改的分支**並執行以下命令: ``` git merge [branch-name] # Merge the given branch into the active branch ``` 在這裡,由於我們位於分支`test`上,因此我們應該使用`git checkout`命令**切換到分支`master`** ,然後使用我們要合併的分支的名稱*(在本例中為“test”)*執行`git merge`命令。 ![Linux 終端機的螢幕截圖,執行命令“git checkout”,切換到 master 分支,然後“git merge”,顯示結果。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a6tqap1uu5gjipkety6w.png) 透過這樣做,在分支`test`上完成的所有工作*(在本例中為`style.css`檔案的建立)*將合併到分支`master`中。 ![模擬兩個分支之間的合併過程的 GIF。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3hs17m005ogm0qlbedjy.gif) ### 7.4 合併衝突 如果**在同一行上更改了一個或多個檔案**並且合併無法**自動**完成,則使用`git merge`合併不同分支可能會導致一些**衝突**。 ![執行「git merge」命令的 Linux 終端機的螢幕截圖,該命令傳回衝突警告。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9mwedudsff1yf8kpzguc.png) 出現這種情況時,我們可以執行`git status`指令來檢查**哪些檔案**有衝突。 ![出現合併衝突警報後執行「git status」指令的 Linux 終端機的螢幕截圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hcfpmta2yiy1xpyc729u.png) 在繼續合併之前,我們需要**解決衝突**,方法是定義應該進行哪些更改,或檢查更改以使它們相互相容。為此, **GIT 將在衝突文件中插入標記**以協助解決問題。 ![在文字編輯器中開啟的衝突檔案的螢幕截圖,顯示了 GIT 建立的用於幫助解決衝突的標記。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a0e727le3ogmhtuq0g7w.png) 解決衝突後,我們只需要將修改過的檔案放回舞台,提交新的無衝突版本,然後再次執行`git merge`指令,這一定會成功合併,沒有任何問題。 8. 與遠端倉庫同步<a name="chapter-8"></a> ---------------------------------- 我們已經知道可以**將本地存儲庫連接到遠端存儲庫**並遠端同步我們的所有工作,使其**保持最新**。 為此,我們需要執行`git push`命令,該**命令將所有提交從本地存儲庫發送到遠端存儲庫**,但首先我們需要\*\*配置遠端存儲庫。 ### 8.1 配置遠端倉庫 啟動*遠端儲存庫*非常簡單。這裡我們將使用**GitHub**來完成它。 首先,我們需要在 GitHub 帳戶中**啟動一個新的空白儲存庫***(只需選擇一個名稱並點擊「建立儲存庫」)* : ![GitHub 上儲存庫建立頁面的螢幕截圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ug1aw5eq15du36vd1hri.png) 接下來,我們需要透過在本機儲存庫中執行以下命令**來配置遠端儲存庫和本機儲存庫之間的關係**: ``` git remote add origin [remote-repository-url] ``` ![Linux 終端機執行「git Remote」命令並顯示結果的螢幕截圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rhrlfg0f0pgljl5b18vl.png) > `git remote -v` -> 顯示實際連接到本機儲存庫的遠端儲存庫的 URL。 正確**連接**遠端儲存庫後,我們需要使用指令`git branch -m main`**將本機分支`master/main`的名稱變更**為「main」 *(如果您的本機分支已稱為`main` ,請忽略此步驟)* : ![Linux 終端機執行「gitbranch」指令、將「master」分支重新命名為「main」並顯示結果的螢幕截圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f0al7joro01pch0ac124.png) > 保持本機儲存庫的主分支與我們要推送到的遠端儲存庫的主分支同名非常重要。 最後,完成上述步驟後,我們可以使用以下命令首次將本機儲存庫與遠端儲存庫**同步**: ``` git push -u origin main ``` ![執行「git push」命令的 Linux 終端機的螢幕截圖,該命令需要 GitHub 身份驗證。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fvkdyis8y989xron52nc.png) 當我們執行`git push -u origin main`指令時,我們可能需要輸入**GitHub 憑證***(使用者和存取權杖)* 。 > 如果您不知道**GitHub 存取令牌**是什麼,或者您沒有設定存取令牌, [請按一下此處](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-personal-access-token-classic)。 > > 我們也可以透過**使用 GitHub CLI 設定身份驗證**來解決此問題。 [按此處](https://docs.github.com/en/get-started/getting-started-with-git/caching-your-github-credentials-in-git)了解具體方法。 經過**身份驗證**後, `git push`應該會成功執行,將本地儲存庫中的所有提交與遠端儲存庫同步。 ![Linux 終端機的螢幕截圖,顯示 GitHub 驗證後繼續執行「git Push」命令。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vp7q4htszkzrfc6vepcl.png) ![收到帶有新檔案的「git Push」後 GitHub 上的遠端儲存庫的螢幕截圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2rqfhi6s6jh369tseh5y.png) ### 8.2 第一次後的Git推送(git推送) 完成上述所有步驟後,可以單獨使用`git push`指令完成**新同步**,無需任何其他參數,如下所示。 ![Linux 終端機執行「git status」、「git commit」和「git Push」命令、執行新提交並將更新推送到遠端儲存庫的螢幕截圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aoatcspiwosywih07nsm.png) ![收到新更新後 GitHub 上的遠端儲存庫的螢幕截圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jskxpghboi62mqw2qcb2.png) > 在這種情況下,使用**GitHub CLI**繞過了執行命令`git push`所需的身份驗證。您可以[點擊此處](https://docs.github.com/en/get-started/getting-started-with-git/caching-your-github-credentials-in-git)了解具體方法。 ### 8.3 更新本地倉庫(git pull) 使用**分散式**遠端儲存庫,可以**遠端**進行更改*(直接在遠端儲存庫中)* ,從而導致我們的本機儲存庫**變得過時**。 考慮到這一點,**更新本機儲存庫**並同步我們在遠端儲存庫中獲得的任何變更非常重要,**以確保本機專案始終具有遠端儲存庫中可用的最新版本**。為此,我們可以執行以下命令: ``` git pull ``` 想像一下,一個**新檔案**`README.md`已**直接在我們的遠端儲存庫中**建立,因此我們的本機儲存庫現已過時。 ![遠端儲存庫的螢幕截圖,其中遠端新增了新的 README.md 檔案。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hccw00vyr7j6lcfm02d2.png) 在本機儲存庫中,我們可以使用上面提到的`git pull`**同步**遠端儲存庫中的變更。 ![Linux 終端機執行「git pull」命令的螢幕截圖,使用遠端儲存庫中的新變更更新本機儲存庫。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/it9ylx1imd94yey5d0wd.png) > 當我們執行`git pull`指令時回傳的前 7 行是`git fetch`指令的回傳。換句話說,如果我們執行`git pull`命令而不先執行`git fetch`命令,GIT 將同時執行這兩個命令以從遠端存儲庫檢索更新並將其同步到本地存儲庫。 > > `git fetch` -> 從遠端儲存庫取得更新,但不同步本機儲存庫(需要`git pull` )。 9. 結論<a name="chapter-9"></a> ----------------------------- 這一切讓我們確信GIT是程式設計師日常生活中必備的版本控制系統,了解它的主要指令和用途可以成為我們技術資歷的轉捩點。最後,隨著本地和遠端儲存庫的同步和更新,以及我們迄今為止所學到的一切,我們已經準備好繼續推進這個令人敬畏的版本控制系統的實用性。 10. 參考文獻<a name="chapter-10"></a> --------------------------------- - [GIT 的官方文件。](https://git-scm.com/docs/git#_git_commands) - [\[PT-BR\] GIT:入門迷你課程(45 分鐘內學會) - Codigo Fonte TV](https://youtu.be/ts-H3W1uLMM?si=-hKGkUmwgT2lZJwy) --- 原文出處:https://dev.to/reenatoteixeira/everything-that-you-need-to-know-about-git-2440

Deno 入門

如果你錯過了,Node 的建立者 Ryan Dahl 的新 Javascript 和 Typescript runtime[已發布](https://deno.land/)!它有一些非常酷的功能,可供公眾使用!讓我們來看看一些簡潔的功能,並開始建立一個簡單的 hello world! ## 什麼是 Deno? Deno 是 Typescript(和 Javascript)的新runtime,主要用 Rust 寫。它有一些[偉大的目標](https://deno.land/manual.html#goals)和一些非常有趣的“非目標”,例如不使用`npm`並且沒有package.json。 ## 安裝 安裝 deno 就像執行以下命令一樣簡單: `curl -fsSL https://deno.land/x/install/install.sh |噓` 然後複製“export”行並將其新增至“~/bashrc”或“~/bash_profile”中。 打開一個新終端並執行“deno”。您應該會收到“>”提示。輸入“exit”,讓我們深入研究一些功能! ## Deno 中的酷功能 ### 預設打字稿 預設情況下,整合 Deno 來執行 Typescript 檔案。它基本上使 Javascript 中的類型成為一等公民。不再需要透過 Babel 編譯來在伺服器端 Javascript 中使用 Typescript。 ### 從 URL 導入 Deno 允許您從網頁匯入,就像在瀏覽器中一樣。只需在您通常命名模組的位置新增一個 URL: ``` import { bgBlue, red, bold } from "https://deno.land/std/colors/mod.ts"; ``` ### 標準庫 此外,Deno 有一個易於導入和使用的標準函式庫。有些模組可以執行多種不同的操作,例如 HTTP 處理、日期時間工作和檔案系統工作。您可以在[此處](https://github.com/denoland/deno_std)查看。 ### 使用 ES 模組 最後,Deno 僅支援 ES 模組語法,這表示不再需要 `require()` 語句,只需良好的 ole' `import x from "y"`。 ## 你好世界範例 讓我們快速看一下 Hello World,其中重點介紹了其中一些功能! 將其複製到“hello-world.ts”檔案中。 ``` import { bgBlue, red, bold } from "https://deno.land/std/colors/mod.ts"; const sayHello = (name: string = "world") => { console.log(bgBlue(red(bold(`Hello ${name}!`)))); } sayHello(); sayHello("Conlin"); ``` 現在您可以使用“deno hello-world.ts”執行它,它應該會列印出一些內容。 將“sayHello”呼叫之一更改為“sayHello(15);”並重新執行它。您應該看到類型錯誤,因為 15 不是字串!太酷了! 您還會注意到如何從 URL 導入 - 它從標準庫中獲取一些控制台顏色內容! # 最後的想法 Deno 還沒有完全準備好用於生產 - 有幾個 [bug](https://deno.land/benchmarks.html#req-per-sec),但開發正在快速推進!這絕對是一個很酷的新開源專案,值得關注! --- 原文出處:https://dev.to/wuz/getting-started-with-deno-e1m

您需要了解的 42 個 🐍 Python 函式庫 🦾

## 簡介 透過這份備忘清單深入了解 Python,其中包含任何 Pythonista 都需要了解的唯一函式庫。 從資料操作到機器學習和建立 Web 應用程式,這些程式庫在您的 Python 編碼之旅中至關重要。 ![介紹 GIF](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6s1cu1kjpp4xae20gvpt.gif) --- ## 網路應用程式 ![Web 應用程式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t532en00kn1s788ndnnt.png) ### 1. [太皮](https://github.com/Avaiga/taipy) Taipy 是這個街區的新來者。 它專為輕鬆開發前端 (GUI) 和 ML/資料管道而設計。 建立您夢想的應用程式得益於: - 完整的客製化和互動 - 多頁和多用戶應用程式 - 管道圖形編輯器 - 還有更多! --- ![QueenB](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ovcc5kqd8xr9uihrggbb.gif) 您的支持意義重大🌱,並且在許多方面為我們帶來了很大的幫助,例如寫文章! 🙏 --- ### 2. [Streamlit](https://github.com/streamlit/streamlit) Streamlit 是一個完善的函式庫,可用於為飛行員快速建立 Web 應用程式。非常容易使用! --- ## 要點 ![要點](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f4ui7ramgta16rsnwm6s.png) ### 3. [熊貓](https://github.com/pandas-dev/pandas) 該庫帶來了兩個核心概念:資料幀和系列,使資料清理和準備成為一個輕鬆的過程。 ### 4. [Numpy](https://github.com/numpy/numpy) Pandas 有資料框,而 Numpy 有陣列。 它們以允許快速資料操作而聞名,使 Numpy 成為科學計算的重要工具。 ### 5. [請求](https://github.com/psf/requests) 該程式庫使處理 HTTPS 請求變得輕而易舉。 Requests 提供與 Web API 互動和管理 HTTP 回應的功能。 ### 6. [Scipy](https://github.com/scipy/scipy) Scipy 基於 Numpy,核心功能專注於數學計算,具有最佳化、訊號處理和插值等功能。 --- ## 約會時間 ![日期時間](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9k1rcy4cduac7r77zkmc.png) ### 7. [日期時間](https://docs.python.org/3/library/datetime.html) DateTime 是一個標準的 Python 函式庫,對於處理任何 DateTime 格式都是必不可少的。 ### 8. [擺](https://github.com/sdispater/pendulum) Pendulum 具有更高級的日期和時間處理所需的附加功能。 他們有更好的時區支援以及更好的格式選項。 --- ## 機器學習 ![機器學習](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o34j1iqk4hipnvtqc3l6.png) ### 9. [Scikit-Learn](https://github.com/scikit-learn/scikit-learn) 這個庫不再需要介紹了,這是理所當然的。 Scikit Learn 是機器學習的參考,包含從聚類到分類的演算法。 它還包括從資料驗證到資料選擇的所有功能。 ### 10. [XGboost](https://github.com/dmlc/xgboost) 該庫以其回歸和分類演算法的高效結果而聞名。 ### 11. [Catboost](https://github.com/catboost/catboost) Catboost 是一個機器學習庫,專門設計用於處理主要顯示分類資料的資料集。 --- ## 深度學習 ![深度學習](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oc0hnfiemtkc74lk981j.png) ### 12. [TensorFlow](https://github.com/tensorflow/tensorflow) TensorFlow 是一個成熟的深度學習庫,專門從事自然語言處理和影像分類。 ### 13. [PyTorch](https://github.com/pytorch/pytorch) Pytorch 還是 TensorFlow,這就是問題所在。 最終,您可以選擇自己的團隊,但 PyTorch 的與眾不同之處在於它更注重自然語言處理,並且更具 Python 風格,從而減少了眾所周知的 TensorFlow 陡峭的學習曲線。 ### 14. [Keras](https://github.com/keras-team/keras) Keras 是開始深度學習的好方法,因為它在 TensorFlow 之上執行,但實作過程得到簡化。 ### 15. [OpenCV](https://github.com/opencv/opencv) OpenCV 提供了各種圍繞即時電腦視覺的演算法。 您可以處理多種格式,包括物件、人類,甚至手寫體。 --- ## 自然語言處理 ![NLP](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i2vh6hm8ambihevofx3t.png) ### 16. [NLTK](https://github.com/nltk/nltk) NLTK 是自然語言處理的首選函式庫。 NLTK 的主要功能包括:處理和操作文本(標記化、詞幹提取等)以及使用 NLP 任務進行分類以進行情緒分析。 ### 17. [SpaCy](https://github.com/explosion/spaCy) 是這個領域的新人,專注於讓 NLP 更容易存取和用戶友好。 該圖書館優化了流程,以確保更高的速度和效率。 --- ## 測試 ![測試](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7711x9xwpfi249kgj1iy.png) ### 18. [Pytest](https://github.com/pytest-dev/pytest) Pytest 是一個簡化測試編寫和執行的框架。它的語法簡潔,使用者友善。 ### 19. [Unitest](https://docs.python.org/3/library/unittest.html) Unistest 是 Python 內建的測試框架。 其主要功能是:測試發現、夾具支援、輕鬆組織和測試套件管理。 --- ## 聲音的 ![音訊](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zrsy4w7kye7q71g7ugld.png) ### 20. [AudioFlux](https://github.com/libAudioFlux/audioFlux) Python 中用於音訊訊號處理的首選庫,但很簡單。 AudioFlux 具有大量功能,包括聲音分析,可用於深度學習訓練。 ### 21. [Librosa](https://github.com/librosa/librosa) 此 Python 程式庫允許從音訊來源中分析和提取特徵。 --- ## 程式碼分析 ![程式分析](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dhbzed8w9wadmdptd4yd.png) ### 22.[黑色](https://github.com/psf/black) 它是一個自動程式碼格式化程式。 它將自動格式化您的程式碼,以在整個專案中保持一致的風格。 ### 23. [Pylint](https://github.com/pylint-dev/pylint) 顧名思義,Pylint 是一個 linter。 它是一個靜態程式碼分析工具,用於檢查程式碼品質和錯誤。 ### 24. [Flake8](https://github.com/PyCQA/flake8) 這是另一個 linting 函式庫,可以根據 PEP8 編碼約定檢查您的程式碼。 ### 25. [Ruff](https://github.com/astral-sh/ruff) Ruff 是等效 linter 的最快選擇。 它提高了效率和速度,使流程加快了十倍。 --- ## 分散式計算 ![分散式計算](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/foog7hfgk5r01vpfu7nl.png) ### 26. [Dask](https://github.com/dask/dask) Dask 是一個流行的分散式運算 Python 包,因為它在處理大型資料集時特別有用。 Dask 整合了 Pandas、Numpy 和 Scikit-learn API,因此易於使用。 ### 27. [PySpark](https://github.com/apache/spark/tree/master) 顧名思義,PySpark 是 Apache Spark 的 Python API,讓我們可以直接在 Python 中利用 Spark 的功能。 ### 28. [極地](https://github.com/pola-rs/polars) Polars 是一個為處理大型資料集而建立的 DataFrame 函式庫。 它的靈感來自蟒蛇皇室 - 熊貓,但有一個(快速)扭曲,它的速度快了 10 到 100 倍。 --- ## 文件 ![文件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tmv4jhi7w8oo3hrr3adp.png) ### 29. [Mkdocs](https://github.com/mkdocs/mkdocs) Mkdocs 是產生簡單文件的最易於存取的庫。 適合較小的專案,幾乎沒有學習曲線。 ### 30. [獅身人面像](https://github.com/sphinx-doc/sphinx) Sphinx 通常是大型專案的首選。 它包括對多種格式的支援並允許特定的自訂。 ### 31. [Pydoc](https://docs.python.org/3/library/pydoc.html) Pydoc 已整合到 Python 生態系統中。它直接從您的模組產生文件。 --- ## 地理資料 ![地理資料](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zq7xis1kydzgxu7h1pm2.png) ### 32. [Geopy](https://github.com/geopy/geopy) Geopys 的主要功能是:距離計算、地理編碼和反向地理編碼。 ### 33. [表](https://github.com/python-visualization/sheet) 該庫允許您使用 Python 建立互動式地圖。改變遊戲規則的人。 ### 34. [Geopandas](https://github.com/geopandas/geopandas) 當您擁有地理空間資料時,您應該採取的方法。 如標題所述,Geopandas 是 Pandas,但用於地理空間資料。該庫具有輕鬆操作和分析地理資料的功能。 --- ## 遊戲 ![遊戲](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xdsaapo3h5bo2dhcj8fs.png) ### 35. [Pygame](https://github.com/pygame/pygame) Pygame 是首選、簡單的函式庫,可以輕鬆使用 Python 建立 2D 和互動式視訊遊戲。 ### 36. [街機](https://github.com/pythonarcade/arcade) 就像 PyGame 一樣,Arcade 使 Python 中建立影片遊戲成為一個有趣的過程。 它們對經典 Pygame 進行了更現代的改造,因此選擇實際上取決於個人喜好。 --- ## 網頁抓取 ![網路搜尋](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kt6wd4ytgpdvuys1mytg.png) ### 37. [Scrapy](https://github.com/scrapy/scrapy) Scrapy 是一個成熟的函式庫,以網頁抓取而聞名。 一些關鍵功能包括:支援非同步/同步操作、HTTPS 請求處理等。 它具有廣泛的功能,這可能證明該庫具有陡峭的學習曲線。 ### 38. [美麗湯](https://www.crummy.com/software/BeautifulSoup/#Download) Beautiful Soup 是您處理從 XML 和 HTML 檔案中提取資料所需的一切。 由於其 Python 風格,它受到了開發人員的讚賞。 --- ## 視覺化 ![視覺化](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j8sawtir7wvwzmtns78i.png) ### 39. [Matplotlib](https://github.com/matplotlib/matplotlib) Matplotlib 是 Python 中主要的元件庫,這是有充分理由的。 Matplotlib 允許使用多種圖表類型繪製 2D 圖形,並且還允許進行大量自訂。 元素的細粒度控制是該庫的真正優勢。 ### 40. [散景](https://github.com/bokeh/bokeh) 與 Matplotlib 相反,Bokeh 專注於互動式圖表。 ### 41. [Seaborn](https://github.com/mwaskom/seaborn) Seaborn 建構在 Matplotlib 之上。 雖然 Matplolib 強調精確性和簡單性,但 Seaborn 在建立複雜的統計視覺化的同時,其時尚的視覺效果具有真正的附加價值。 ### 42. [Vizzu](https://github.com/vizzuhq/vizzu-lib) Vizzu 在視覺化領域找到了自己的定位,並且做得非常好。 他們將講故事和圖表與高度動畫的視覺化融為一體,這是一種獲得更多動態圖表的好方法。 --- ## 結論 無論您是高級 Python 專家還是正在嘗試 Python,有了這份不可或缺的函式庫列表,您將能夠應對任何挑戰。祝你編碼愉快! --- 我是一名新手作家,歡迎任何改進建議! ![新秀圖片](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/25oebh36ha622u74kpli.gif) 如果您有任何疑問,請隨時與我們聯繫。 --- 原文出處:https://dev.to/taipy/top-42-python-libraries-you-need-to-know-1omo

Linux 指令備忘單

碰巧有些 Linux 終端機命令很難記住,將它們作為備忘單保存在電腦或紙上是一個很好的做法。此列表並不詳盡,但包含最常用的命令。請隨意在下面的評論中加入您最常用的命令並分享此列表✌️。 ## 用戶 - **Id** – 有關使用者的詳細資訊(uid、gid 和群組)。 - **last** – 列出有關最近登入的訊息,包括時間、使用者名稱、IP 位址和會話持續時間。 - **who** – 顯示授權使用者。 - **groupadd "testgroup"** – 建立一個名為「testgroup」的群組。 - **adduser NewUser** – 新增名為「NewUser」的使用者。 - **userdel NewUser** – 刪除名為「NewUser」的使用者。 - **usermod NewUser** – 修改使用者「NewUser」的資訊。 ## 目錄導航 - **cd /**- 導覽至根目錄。 - **cd** - 導航到主目錄(使用 $HOME 變數)。 - **cd /root** - 導覽至 /root 目錄。 - **cd ..** - 向上移動一級。 - **cd /root/.ssh** - 導航到隱藏資料夾 .ssh。 ## 使用文件 - **ls -al** – 顯示目前資料夾中的檔案和目錄。 - **pwd** – 顯示目前工作目錄。 - **mkdir NewFolder** – 建立一個名為「NewFolder」的新目錄。 - **rm NewFile** – 刪除名為「NewFile」的檔案。 - **rm -f NewFile** – 強制刪除名為「NewFile」的檔案。 - **rm -r NewFolder** – 遞歸刪除名為「NewFolder」的目錄。 - **rm -rf NewFolder** – 強制遞歸刪除名為「NewFolder」的目錄。 - **cp oldfile1 newfile2** – 將「oldfile1」的內容複製到「newfile2」。 - **cp -r olddir1 newdir2** – 遞歸地將目錄「olddir1」複製到「newdir2」。如果 Dir2 不存在,則會建立它。 - **mv oldfile1 newfile2** – 將「oldfile1」重新命名為「newfile2」。 - **ln -s /etc/log/file logfile** – 建立到檔案的符號連結。 - **touch newfile** – 建立一個名為「newfile」的空白檔案。 - **cat > newfile** – 取得 STDIN 並將其放入「newfile」中。 - **head newfile** – 輸出檔案「newfile」的前 10 行。 - **tail newfile** – 輸出「newfile」的最後 10 行。 - **gpg -c newfile** – 使用密碼以 gpg 格式加密「newfile」並將其儲存在同一目錄中。 - **gpg newfile.gpg** – 解密 gpg 檔案。 - **wc newfile** – 顯示新檔案中的位元組數、字數和行數。 ## 檔案/目錄權限 - **chmod 777 /root/ssh** – 為有權存取伺服器的每個人(擁有者、群組、其他人)設定讀取、寫入和執行權限。 - **chmod 755 /root/ssh** – 將擁有者的權限配置為 rwx,將群組和其他人的權限配置為 r_x。 - **chmod 766 /root/ssh** – 設定擁有者的 rwx 以及群組和其他人的 rw。 - **chown newuser newfile** – 將 newfile 的擁有者改為 newuser。 - **chown newuser:newgroup newfile** – 將 newfile 的擁有者和群組擁有者變更為 newuser 和 newgroup。 - **chown newuser:newgroup newfolder** – 將目錄 newfolder 的擁有者和群組擁有者變更為 newuser 和 newgroup。 - **stat -c “%U %G” newfile** – 顯示 newfile 的使用者和群組擁有者。 ## 搜尋 - **grep searchargument newfile** – 在 newfile 中搜尋 searchargument。 - **grep -r searchargument newfolder** – 遞歸搜尋 newfolder 中所有檔案中的 searchargument。 - **定位新檔案** – 顯示新檔案的所有位置。 - **find /etc/ -name "searchargument"** – 在 /etc 目錄中尋找名稱以 searchargument 開頭的檔案。 - **find /etc/ -size +50000k** – 在 /etc 目錄中尋找大小大於 50000k 的檔案。 ## 檔案 - **tar -cf archive.tar newfile** – 從檔案「newfile」建立檔案「archive.tar」。 - **tar -xf archive.tar** – 提取檔案「archive.tar」的內容。 - **tar -zcvf archive.tar.gz /var/log/** – 從 /var/log/ 目錄建立檔案並使用 gzip 對其進行壓縮。 - **gzip newfile** – 壓縮新檔案(副檔名為 .gz)。 ## 從套件中安裝程式 - **rpm -i pkg_program.rpm** – 在 CentOS、RHEL 等上安裝 RPM 軟體包。 - **rpm -e pkg_name** – 刪除 CentOS、RHEL 等上的 RPM 軟體包。 - **dnf install pkg_name** – 在 CentOS、RHEL 等上使用 DNF 從儲存庫安裝軟體包。以前使用 YUM,但最近已被 DNF 取代。 - **dpkg -i pkg_name** – 從 Debian、Ubuntu、Mint 等上的 DEB 軟體包安裝。 - **dpkg -r pkg_name** – 刪除 Debian、Ubuntu、Mint 等上的 DEB 軟體包。 - **apt install pkg_name** – 在 Debian、Ubuntu、Mint 等上從儲存庫安裝軟體套件。 - **apt remove pkg_name** – 移除 Debian、Ubuntu、Mint 等上的軟體套件。 - **apt update && apt update** – 更新系統中的軟體包(Debian、Ubuntu、Mint 等)並更新儲存庫。 ## 流程 - **ps** – 顯示目前正在執行的進程。 - **ps aux | grep 'bash'** – 尋找 'bash' 的程序 ID (PID)。 - **pmap -x 11** – 在進程記憶體中映射 PID 11 的進程。 - **top** – 顯示所有正在執行的進程。 - **kill pid** – 透過 PID 終止進程。 - **killall process** – 終止名為「process」的所有程序。 - **pkill process-name** – 按名稱向程序發送訊號。 - **bg** – 將掛起的程序傳送到背景。 - **fg** – 將正在執行的進程帶到前台。 - **fg process** – 將名為「process」的進程帶到前台。 - **lsof** – 列出進程開啟的檔案。 - **renice 19 PID** – 設定進程的最低優先權。 - **pgrep bash** – 尋找「bash」的進程 ID。 - **pstree** – 顯示進程的樹狀表示。 ## 系統 - **uname** – 顯示系統資訊。 - **uname -r** – 顯示有關 Linux 核心的資訊。 - **hostname** – 顯示主機名稱。 - **hostname -i** – 顯示主機的 IP 位址。 - **date** – 顯示日期和時間。 - **timedatectl** – 輸出和修改日期和時間設定。 - **cal** – 顯示日曆。 - **w** – 顯示目前登入的使用者。 - **whoami** – 顯示您的使用者名稱。 - **finger root** – 顯示有關 root 使用者(需要使用「apt-get install Finger」的資訊進行安裝)。 ## 硬體指令 - **dmesg** – 在啟動期間顯示系統訊息。 - **cat /proc/cpuinfo** – 顯示有關處理器的資訊。 - **cat /proc/meminfo** – 顯示有關記憶體的資訊。 - **lshw** – 顯示有關裝置的詳細資訊。 - **lsblk** – 顯示有關區塊裝置的資訊。 - **free -m** – 釋放記憶體:RAM 和交換(切換 -m 表示 MB)。 - **lspci -tv** – 在樹狀圖視圖中顯示 PCI 裝置資訊。 - **lsusb -tv** – 在樹狀圖視圖中顯示 USB 裝置。 - **dmidecode** – 顯示有關 BIOS 設備的資訊。 - **hdparm -i /dev/xda** – 顯示有關磁碟的資訊。 - **hdparm -tT /dev/xda** – 顯示 xda 的讀寫速度。 - **badblocks -s /dev/xda** – 執行壞扇區測試。 ## 光碟管理指令 - **df -h** – 顯示已安裝分割區上的可用空間(以位元組為單位)。 - **df -i** – 顯示檔案系統中的空閒 inode。 - **fdisk -l** – 提供有關磁碟、分割區和檔案系統的資訊。 - **du -sh** – 顯示已安裝分割區上的未分配空間(以 MB、GB、TB 為單位)。 - **findmnt** – 顯示所有安裝點。 - **mount /dev/sdb1 /mnt** – 將 sdb 磁碟的分割區 1 掛載到 /mnt 目錄。 ## 網絡 - **ip addr show** – 顯示所有可用網路介面的 IP 位址。 - **ip address add 192.168.0.1/24 dev eth0** – 將位址 192.168.0.1 指派給 eth0 介面。 - **ifconfig** – 顯示所有可用網路介面的 IP 位址。 - **ping 192.168.0.1** – 發送 ICMP 協定請求以連接到 192.168.0.1 處的節點。 - **whois 網域** – 顯示有關網域的資訊。 - **dig 網域 **– 檢索有關網域的 DNS 資訊。 - **dig -x 192.168.0.1 ** – 執行反向 DNS 解析。 - **host serverspace.us** – 解析主機位址。 - **hostname -I ** – 顯示本機位址。 - **wget file_name(連結到檔案)** – 下載檔案。 - **netstat -pnltu ** – 顯示主機上正在偵聽的所有連接埠(需要「apt-get install net-tools」)。 ## 遠端連線 - **ssh root@host** – 以 root 使用者身分透過 ssh 連線到遠端主機。 - **ssh -p port_number user@host** – 使用非預設 ssh 連接埠連接到遠端主機,指定使用者。 - **ssh host** – 使用目前使用者的預設連線。 - **telnet host** – 使用 telnet 連線(連接埠 23)。 --- 原文出處:https://dev.to/serverspace/linux-commands-cheat-sheet-aif

🫵 開發人員可實現的 5 項副業💰

嘿嘿👋 在您作為開發人員的旅程中,賺錢的常見方法是**獲得全職工作**。 然而,您可能還沒有找到工作(_又名您仍在學習_),或者您已經開始工作,但您正在尋找賺取額外現金的方法。 現在,您可以嘗試透過多種方式賺取副收入。 “有些比其他更現實。” 在本文中,我們將了解您今天就可以開始的**_可實現的_副業收入工作**。 深吸一口氣,讓我們用這些新知識洗滌我們的靈魂。 🧎 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uv5gxnqnmz2lixw86fix.gif) **_免責聲明:_** 我沒有嘗試清單中的每個選項。如果您認為應該在清單中加入一些內容或您想分享個人經歷,請在下面發表評論(我很樂意聽取您的意見!)。 🙇‍♂️ --- ## ⚔️ 創作者任務 在 Quine,我們目前正在為開發人員提供一種將其技能貨幣化的方法。 _Creator Quests_ 是每兩週發生一次的開源挑戰。 **這就像一場 24/7 的黑客馬拉松,獎勵開發者建立酷炫的應用程式**以及使用未來的開發者工具。 🚀 社區透過對他們喜歡的專案給予榮譽來決定獲勝者。獲得最多榮譽的專案將獲得最多的收益。 🤑 **下一次挑戰將於 12 月 19 日星期二開始。** 要參加,請註冊 [Quine](https://quine.sh/?utm_source=devto&utm_campaign=monetising_dev_skills) 並前往 _Quests_。 PS:測試期間,100%有效參賽者均獲得獎勵💸 目前的獎金池為 1024 美元,隨著更多參與者的加入,獎金池將會增加!點擊下面的並試試看! ⬇️ [![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/akiuhk62zctvf3b9gilx.png)](https://quine.sh/?utm_source=devto&utm_campaign=monetising_dev_skills --- # 💃 MaaS - 我即服務 **自由工作者很難開始。** 然而,每個人都可以**實現並獲得**。 我在資料分析方面有一些自由職業經驗。如果我必須重做一次,我會採取以下方法: **1️⃣ 選擇平台:** 了解[Fiverr](https://www. Fiverr.com/)、[Upwork](https://www.upwork.com/en-gb/nx/job)之間的區別-post/instant/welcome) 和 [自由工作者](https://www.freelancer.co.uk/)。選擇一個您喜歡的平台並專注於此。我發現 [Malt](https://www.malt.com/) 是一個有趣的平台,但如果你認為自己非常優秀,你可以隨時關注 [TopTal](https://www.toptal.com) / )。 **2️⃣ 不要成為萬事通先生/女士:** 圍繞非常具體的服務建置配置文件,例如_我專門從事Python 抓取工具的編碼並使用MongoDB 建置資料庫,最終通過Plotly 顯示儀表板_(不完全是這樣)但你明白了🙃)。 **3️⃣ 為您的第一個客戶不收取任何費用:** 獲得您的第一個客戶非常困難,因此請聯繫招聘訊息並說明您很樂意**免費這樣做。** 如果他們對這份工作感到滿意,請詢問他們提供良好的評級。 **4️⃣ 獲得您的第一筆薪水:** 開始為您的工作收費 - 仍然以較低的費率 - 並建立您的聲譽。 **5️⃣ 提高定價:** 一旦您在平台上擁有更強大的地位,您就可以決定提高定價。 我的最後評論是,雖然我相信每個人都可以透過自由工作開始賺錢,但**我不認為每個人都應該這樣做。** 有很多缺點不符合你喜歡的工作方式(難纏的客戶、截止日期) 、平台依賴性等)。 **💁 特別提示:** 在倫敦,我發現了一個吸引一些客戶的小技巧。您可以聯繫一些相關的諮詢/招聘機構,他們可以幫助您找到客戶。如果您在起步時遇到困難,請考慮這樣的機構。 --- ## 🧪 測試一下。獲得報酬。 作為開發人員,您了解網頁或應用程式背後的技術細節。 這意味著您有能力執行出色的品質檢查。 根據您關注的平台,您可以花 10 到 60 分鐘以上嘗試應用程式或網站。 市面上有各種平台,但您可以查看的 3 個已知網站是: - [Trymata](https://trymata.com/) - [使用者測試](https://www.usertesting.com/) - [UserLytics](https://www.userlytics.com/user-experience-research/paid-ux-testing/) PS:還有一個完整的調查選項,在我看來,花費很少。如果您仍然好奇,可以查看[Wynter](https://wynter.com/participants/join)或[SwagBucks](https://www.swagbucks.com/g/paid-surveys)。 --- # 🐛 蟲子獵人 如果您對細節有敏銳的洞察力並且喜歡網路安全,那麼您可以透過這項技能獲利。 如果你有好奇心並且有良好的程式設計技能,你就可以在那裡賺錢。 🥂 一開始你可能會得到 20 美元的報酬,但獎勵可能會增加到天文數字,例如 10 萬英鎊以上。 我要強調的是,這不是你成為百萬富翁的方式。有一些不錯的競爭,你可能不會賺到很高的錢。 您仍然應該嘗試一下,看看它是否適合您。 最知名的平台是: - [HackerOne](https://www.hackerone.com/) - [BugCrowd](https://www.bugcrowd.com/) 如果你在這方面變得擅長,你可以考慮大公司,因為這往往是大公司的地方。 您可以從 [Microsoft](https://www.microsoft.com/en-us/msrc/bounty)、[Apple](https://security.apple.com/bounty/) 和 [Google](https: //bughunters.google.com/about/rules/6625378258649088/google-and-alphabet-vulnerability-reward-program-vrp-rules)。 **最後提示:** 如果您發現自己喜歡使用的網站有漏洞,向他們索取賠償總沒有壞處。 🙃 --- ## 🧑‍🏫 你學到了什麼嗎?教它回來 輔導是我個人最喜歡的「副業」。 對於某些人來說,這可能看起來“乏味”,但它是非常可以實現的,並且它**增強您圍繞特定主題的知識,同時賺大錢**。 此外,您不一定需要成為專家。 這是正確的! 只要您在特定領域更有知識,您就可以收取教授該知識的服務費用。 您可以透過 3 種方法來解決此問題: ### 📜 老學校方式 1️⃣ **確定合適的學校**:在學校/學院周圍張貼實體廣告,並附上您的課程和聯絡方式。 2️⃣ **辨識社群:** 尋找並參與相關的 Discord、Facebook 和 Linkedin 群組。以尊重的方式讓相關社區了解您的服務。 3️⃣ **不要太貪心:** 以較低的價格開始您的第一堂課,讓一切順利進行。經過一些經驗後,考慮提高價格。 ### 👶 新學校方式 查看以下平台: - [Codementor](https://www.codementor.io/freelance) - [Superprof](https://www.superprof.co.uk/lessons/computer-programming/united-kingdom/) - [導師](https://tutorhouse.co.uk/a/coding) 註冊成為導師並以低於市場價格的價格開始招募您的第一批學生。 ### 📦 數位內容 您可以考慮建立一些視訊課程。 我個人最喜歡的是一個名為 [Stan Store](https://www.stan.store/?ref=bap&utm_source=stan-store-link&utm_medium=redirect&utm_campaign=storefront) 的新工具。 這是數位創作者的全能工具包,不僅僅是建立影片內容。 > 我個人使用這個平台賺了幾百美元。 或者,您可以查看更傳統的平台,例如 [SkillShare](https://www.skillshare.com/en/search?query=Coding) 或 [Udemy](https://www.udemy.com/)。 --- ## 較不容易實現的路徑(但值得一提)👇 <br> <br> - **🚧 黑客馬拉松**:一些黑客馬拉松提供豐厚的現金獎勵。缺點是通常存在相當多的競爭。要尋找合適的黑客馬拉松,迄今為止最好的網站是 [DevPost](https://devpost.com/)。 <br> - **🏷️ 銷售鍋爐模板:** 您可以根據自己的知識建立鍋爐模板。在這種情況下,「稍微少一點」的是你能賺多少錢(至少在最初)。這是因為它需要大量的追隨者(或大量的行銷)。如果你想嘗試一下,可以看看 [Gum Road](https://gumroad.com/) 和 [AppSumo](https://appsumo.com/)。 --- 我希望您喜歡這篇文章,它可以幫助您了解如何利用您的開發技能來從事副業。 上述演出並不是試圖描繪出你將一夜致富的景象。然而,它們是副業,獲得報酬的機會很高。只要保持一定的一致性,隨著時間的推移,您可以期望獲得更多的收入。 🚀 這篇文章的靈感來自 @lissy93 寫的一篇很棒的文章。 如果您有興趣了解將您的開發技能貨幣化的其他方法(特別是如果您更有經驗),請查看他們的[文章](https://dev.to/lissy93/50-ways-to-bring -in- extra-cash-as-a-developer-19b6) 並給它一些愛。 下週見, 您的開發夥伴💚 巴普 --- 如果您想加入開源中自稱「最酷」的伺服器😝,您應該加入我們的[discord伺服器](https://discord.com/invite/ChAuP3SC5H/?utm_source=devto&utm_campaign=9_deep_learning)。我們隨時為您的開源之旅提供協助。 🫶 {% 嵌入 [https://dev.to/quine](https://dev.to/quine) %} --- 原文出處:https://dev.to/quine/5-achievable-side-hustles-for-developers-4bcg

🔥 NextJS 專案的 12 個頂級庫 🏆

![保存](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/szi0gw4l049yctxjeu1p.png) 在過去的十年裡,我一直是一名全端開發人員,建置了像[gitup](https://gitup.dev/) 這樣的較小專案和像[crosspublic](https://github.com/github-20k/) 這樣的更大專案跨公共)。 多年來,我測試了不同的工具: 1. 提高工作效率 2. bug 更少 3. 少寫程式碼 我整理了一系列庫來幫助您開發我每天使用的優秀 NextJS 東西,並解釋了您可以用它們做什麼。 **讓我們深入了解一下。** ![變得更好](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ap38q1ej3tqypjuebg3u.gif) --- # 1. [Trigger.dev](https://github.com/triggerdotdev/trigger.dev) 使用 NextJS,我總是需要幫助來處理與後台作業相關的所有事情。 它可以是在背景執行的 cron 作業,用於傳送電子郵件或處理系統中的新使用者管道。 這導致我執行另一台伺服器來處理這些作業,無論是外部 EC2 伺服器還是帶有事件橋的無伺服器功能。 這會導致我支付額外的服務費用(管理更多服務)並自行管理水平擴展(在某些時候)。 [Trigger.dev](http://Trigger.dev) 改變了這一點,在 NextJS(以及許多其他)之上提供後台作業。 他們也知道如何解決 NextJS 無伺服器逾時限制來處理長時間執行的作業。   ![TriggerDev](https://nevdav2.dreamhosters.com/wp-content/uploads/2023/12/triggertop.gif) --- ## 2. [Prisma](https://www.prisma.io) Prisma 不是 NextJS 特有的。它是一個與資料庫一起使用的 ORM。 ORM 是資料庫查詢的統一包裝器。 它保持良好的結構,並允許您在不同的資料庫提供者之間快速更改。 雖然您可以使用很多 ORM,但 Prisma 的獨特之處在於為您的查詢提供 Typescript 支持,使一切速度提高 100 倍。 NextJS 在預設配置中使用了 typescript,使其成為完美的匹配。   ![prisma.gif](https://nevdav2.dreamhosters.com/wp-content/uploads/2023/12/prisma.gif) --- ## 3. [NextAuth.js](https://next-auth.js.org) 假設您要實現任何服務提供者身份驗證,例如 Facebook / Google / GitHub (oAuth)。 在這種情況下,您必須為每個提供者建立實作或使用外部服務,例如 [Auth0](https://auth0.com/) 或 [Clerk](https://clerk.com/)。 如果您打算自行執行此操作,NextAuth 提供了豐富的實現,以便您只需提供正確的金鑰即可輕鬆新增它們。 一旦您登錄,他們也會處理授權。 *Next.JS auth 可以與 Prisma 開箱即用。*   ![authjs.gif](https://nevdav2.dreamhosters.com/wp-content/uploads/2023/12/authjs.gif) --- ## 4. [下一個網站地圖](https://github.com/iamvishnusankar/next-sitemap) 在伺服器上部署 NextJS 後,您需要協助 google 索引所有頁面。 如果您可以告訴 Google 您網站上的所有頁面,那就更好了。 為此,您可以建立一個列出所有頁面的 sitemap.xml 檔案。 您可以輕鬆地使用 Next-Sitemap 來實現這一點。   ![sitemap.gif](https://nevdav2.dreamhosters.com/wp-content/uploads/2023/12/sitemap.gif) --- ## 5. [下一步 SEO](https://github.com/garmeeh/next-seo) SEO 是透過向您的網站預覽提供關鍵字、描述和圖像,使您的網站出現在 Google Feed 上以進行不同查詢的過程。 如果您使用新的 NextJS 應用程式路由器,則可能不需要使用它。 您可以使用他們的“導出元資料”方法或“生成元資料”, 但如果您使用舊的應用程式路由器,這是為您的網站加入 SEO 的最佳方式。   ![seo.gif](https://nevdav2.dreamhosters.com/wp-content/uploads/2023/12/seo.gif) --- ## 6. [Zod](https://github.com/colinhacks/zod) Zod 是一個物件驗證器(伺服器和客戶端)。 您可以在物件上放置不同的規則並稍後對其進行驗證,例如使用者名稱和密碼,或更複雜的內容(例如陣列長度或其他鍵上的條件)。 *Zod 不是 NextJS 特定的。* 多年來,我看過很多物件驗證器,例如 [Yup](https://github.com/jquense/yup) 和 [class-validator](https://github.com/typestack/class-validator)。 是的,它看起來不像 Zod 那樣維護,並且在使用 NestJS 之類的東西時,類驗證器非常強大 - 所以你最好使用 Zod。   ![zod.gif](https://nevdav2.dreamhosters.com/wp-content/uploads/2023/12/zod.gif) --- ## 7. [React-hook-form](https://github.com/react-hook-form/react-hook-form) 雖然 Zod 可以驗證物件,但如果沒有自訂邏輯,它不會影響您的用戶端和後端。 React-hook-form 是優秀的用戶端驗證專案(顯示輸入錯誤、管理輸入狀態和提交)。 當然,您可以使用 Zod 作為 React-hook-form 的驗證器。   ![hookform.gif](https://nevdav2.dreamhosters.com/wp-content/uploads/2023/12/hookform.gif) --- ## 8. [tRPC](https://github.com/trpc/trpc) 我承認我以前從未使用過 tRPC,但今天它似乎吸引了許多人的目光。 它與 Prisma 有類似的概念;它們為您的請求和回應產生一個接口,因此當您使用前端呼叫時,您會獲得自動完成功能。 這很好,因為它減少了錯誤的機會 - 假設您修改了後端路由,您將無法編譯專案 - 客戶端將返回不存在的參數或回應鍵的錯誤。   ![trpc.gif](https://nevdav2.dreamhosters.com/wp-content/uploads/2023/12/trpc.gif) --- ## 9. [SWR](https://swr.vercel.app) 和 [React-Query](https://github.com/TanStack/query) 多年來我一直使用 Axios 和 fetch 作為發送請求的基礎庫。 SWR 和 React-Query 增強了這些函式庫並提供鉤子、快取、轉換等。 強烈推薦用於每個專案。請注意,這些庫適用於客戶端元件(“使用客戶端”),而不是伺服器元件。   ![query.gif](https://nevdav2.dreamhosters.com/wp-content/uploads/2023/12/query.gif) --- ## 10. [lodash](https://lodash.com) 這不是 NextJS 特定的函式庫。 它是一個用於改變資料的函式庫,雖然這些年來 JavaScript 憑藉像 flatMap 這樣優秀的原生函數取得了很大的進步,但仍然缺少一些東西,例如按鍵或分塊和陣列的唯一陣列。 我發現自己幾乎在所有專案中都使用 lodash。   ![lodash.gif](https://nevdav2.dreamhosters.com/wp-content/uploads/2023/12/lodash.gif) --- ## 11. [dayjs](https://day.js.org/) day.js 是一個包含與日期、格式、時區等相關的所有內容的函式庫。 我可能會因為那件事而被烤。我多年來一直在使用“moment.js”。 現在它不再維護了,dayjs 是一個不錯的選擇。 有些人喜歡新的 JS 函數來處理日期,但我仍然覺得 dayjs 選項和原生 JS 日期函數之間存在很大的差距。   ![scrolldown.gif](https://nevdav2.dreamhosters.com/wp-content/uploads/2023/12/scrolldown.gif) --- ## 12. [jsdom](https://github.com/jsdom/jsdom) 這不是必須的,但我最近在許多專案中都使用它作為 [cheerio](https://github.com/cheeriojs/cheerio) 的替代品。 您可以取得整個頁面內容(`<html><body>....</html>)` 並將其轉換為稍後可以使用「本機」javascript dom 函數`querySelector`、`innerHTML` 等來操作的物件… 非常適合需要一些刮擦的專案。   ![jsdomer.gif](https://nevdav2.dreamhosters.com/wp-content/uploads/2023/12/jsdomer.gif) --- 我們在 X 上連接嗎? :) [我在這裡](https://twitter.com/nevodavid) 您是否為 NextJS 使用其他一些很酷的程式庫? 請在評論中讓我了解它們:) --- 原文出處:https://dev.to/nevodavid/top-12-libraries-for-your-nextjs-project-1oob