🔍 搜尋結果:HTML

🔍 搜尋結果:HTML

計算機科學基礎仍然很重要。

我很不舒服地承認,2005 年我在微軟工作時,我不知道如何實作 BFS(廣度優先搜尋)。當時,我已經進入專業軟體工程職業生涯六年,並獲得了電腦科學碩士學位。 幾年後我仍然不知道這一點,有一天,在午餐時,有人提到他們之前面試過的候選人「甚至不知道如何找到圖中的最短路徑」。這讓我感覺很可怕——我知道我也做不到。幾秒鐘之內,我就從一個看似成功的微軟軟體工程師變成了一個冒名頂替者。這件事促使我提升了我的電腦科學基礎。 雖然我最終學習了 BFS,但我的例子表明,在軟體工程職業生涯中取得紮實的進步並不需要熟記*[演算法簡介](https://en.wikipedia.org/wiki/Introduction_to_Algorithms)*(又稱 CLRS)。與二十年前相比,今天更是如此。如今,我們正在更高的抽象層次上工作。最常見的演算法,如二分搜尋,都包含在標準庫中,實現它們是浪費時間。 儘管如此,我還是敦促每個開發人員學習電腦科學的基礎知識。 為什麼要學習電腦科學基礎? ------------- 答案很簡單:學習電腦科學基礎可以促進你的職業生涯。方法如下。 **您將很快了解不熟悉的系統**。 一旦你學習了基本的演算法和資料結構,你就會發現它們無所不在。您將意識到 HTML 和 XML 文件是樹,鍵值儲存在概念上可以被視為哈希表,並且從單一消費者的角度來看,Kafka 主題是佇列。這是非常強大的,因為它可以讓您了解這些系統的行為和限制,即使您對它們了解不深。 當我第一次開始使用 git 時,我感到不知所措。我不明白它是如何運作的,這些命令也沒有多大意義。有一天,我在 YouTube 上又看了一篇 git 講解,其中提到 git 是一個 DAG(有向無環圖)。一夜之間,我成為了修復團隊成員儲存庫的 git 專家。 **您將能夠解決具有挑戰性的問題**。 軟體開發人員日常處理的大多數問題不需要先進的電腦科學知識。然而,偶爾會出現一個具有挑戰性的問題。這時了解演算法和資料結構會非常方便。我記得我在一個依賴圖問題上苦苦掙扎了幾天,當時我的同事指出,如果我應用拓撲排序,我可以快速解決它。 **你會在面試程式設計方面做得更好**。 許多面試,尤其是大型科技公司的面試,都包含程式設計問題。通常,這些問題可以使用一種標準演算法來解決。如果您熟悉他們,您將有更好的機會在這些面試中取得好成績。 如何保持技能與時俱進。 ----------- 大多數技能都會隨著時間的推移而退化。演算法技能沒有什麼不同。即使您記得演算法或資料結構背後的想法,隨著時間的推移,細節也會變得模糊。這就是為什麼定期更新你的技能是有好處的。有很多方法可以做到這一點。我最喜歡的是定期參加[Advent of Code](https://adventofcode.com/2023/about)活動。 Advent of Code 是 12 月的線上活動,直到聖誕節之前每天都會向您提出兩個問題。解決這些問題非常有趣,可以讓我提升演算法和解決問題的技能。但最好的部分是*解決方案大線程*——其他人發布解決方案的專用子版塊。一旦解決了當天的問題,我就會檢查這些線程。它們是我從未想到的驚人見解、非常規方法和程式設計技巧的寶庫,我從它們身上學到了很多。 圖片:https://cs.stackexchange.com/a/107190 --- 原文出處:https://dev.to/moozzyk/computer-science-fundamentals-are-still-important-5h5i

2024 年你需要了解的 Python 函式庫

長話短說 ---- 你正在學習Python嗎?這是一片叢林! 您可以擁有任何您能想到的庫 - 從建立遊戲到建立 Web 應用程式。 透過此列表,無論您是剛剛入門還是想要深化 Python 遊戲,都可以快速了解 50 個標準 Python 庫及其用途。 ![介紹](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/at6swte9i2adqyeni03w.gif) --- 1.**Taipy** -------- Taipy 旨在加快應用程式開發,從最初的原型到生產就緒的應用程式。 這個開源 Python 函式庫專為輕鬆開發前端 (GUI) 和 ML/資料管道而設計。 它程式碼量低,專為任何 pythonista 設計。 ![口服](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/scksaelbdhxsyzkv0bdq.png) https://github.com/Avaiga/taipy Star ⭐ Taipy 儲存庫 您的支持意義重大🌱,並在許多方面幫助我們,例如寫文章! 🙏 --- **2.NumPy** ----------- 對於數值計算至關重要,支援大型多維陣列和矩陣。該函式庫是 Python 版稅的一部分。 https://github.com/numpy/numpy Star ⭐ Numpy 儲存庫 --- 3.**Pandas** -------- 資料操作和分析的基石,提供直覺的資料結構和操作來操作數值表和時間序列。又一個Python不可或缺的函式庫,必知的函式庫。 https://github.com/pandas-dev/pandas Star ⭐ Pandas 儲存庫 --- **4.Matplotlib** ---------------- 一種多功能工具,用於建立各種靜態、最小和互動式視覺化。有很多參數可供使用,這個函式庫在繪製 ML 和 AI 圖表時非常有用。 https://github.com/matplotlib/matplotlib Star ⭐ Matplotlib 儲存庫 --- **5.SciPy** ----------- 專注於技術和科學計算,使用 Scipy,您可以進行最佳化、整合、插值等。 https://github.com/scipy/scipy Star ⭐ SciPy 儲存庫 --- **6.Scikit-learn** -------------- 機器學習的首選庫,提供廣泛的監督和無監督學習演算法。開始機器學習時您應該了解的唯一庫。 https://github.com/scikit-learn/scikit-learn Star ⭐ Scikit-learn 儲存庫 --- **7.TensorFlow** ---------------- 機器學習的綜合框架提供了各種工具、庫和社區資源。學習曲線可能有點陡峭,但在 Python 和 ML 領域中了解 TF 很重要。 https://github.com/tensorflow/tensorflow Star ⭐ TensorFlow 儲存庫 --- **8.PyTorch** ------------- 由於其靈活性,提供動態神經網路建立和操作,因此受到學術研究和生產的青睞。 https://github.com/pytorch/pytorch Star ⭐ PyTorch 儲存庫 --- 9.**Keras** -------- 用於建立和訓練深度學習模型的高級 API,旨在促進神經網路的建構和使用。 https://github.com/keras-team/keras Star ⭐ Keras 儲存庫 --- 10.**requests** --------- 簡化了發出 HTTP 請求的過程,使 Web 抓取和 API 消費更容易存取。 https://github.com/psf/requests Star ⭐ 請求儲存庫 --- 11.**Beautiful Soup** ----------- 一種網頁抓取工具,有助於從 HTML 和 XML 文件中提取資料。 https://github.com/waylan/beautifulsoup Star ⭐ Beautiful Soup 儲存庫 --- 12.**Flask** --------- 一個輕量級且可擴展的 Web 框架,非常適合建立中小型 Web 應用程式。 https://github.com/pallets/flask Star ⭐ Flask 儲存庫 --- 13.**Django** --------- 這個高級框架專為快速開發和簡潔、實用的設計而設計。 https://github.com/django/django Star ⭐ Django 儲存庫 --- 14.**Selenium** -------- 該程式庫使 Web 瀏覽器自動化,從而能夠模擬實際使用者操作以測試 Web 應用程式。 https://github.com/SeleniumHQ/selenium Star ⭐ Selenium 儲存庫 --- **15.Pygame** ------------- 提供用於編寫視訊遊戲的 Python 模組,包括圖形和聲音庫。 https://github.com/pygame/pygame Star ⭐ Pygame 儲存庫 --- 16.**Pillow** --------------- 擴充Python圖像庫功能,支援各種圖像檔案格式。 https://github.com/python-pillow/Pillow Star ⭐ Pillow 儲存庫 --- 17.SQL**Alchemy** ------------- 本函式庫提供了一整套透過 Python 處理資料庫的工具,提供了強大的 ORM 層和 SQL 表達式語言。 https://github.com/sqlalchemy/sqlalchemy Star ⭐ SQLAlchemy 儲存庫 --- **18.PySpark** -------------- 從名稱中可以看出,該程式庫將 Apache Spark 的強大功能引入了 Python,透過 Pythonic 方法促進大資料處理和分析。 https://github.com/apache/spark Star ⭐ PySpark 儲存庫 --- 19.**dash** --------- 允許直接在 Python 中建立分析 Web 應用程式,無需深入了解 Web 開發。 https://github.com/plotly/dash Star ⭐ dash 儲存庫 --- 20.**Plotly** --------- 專注於建立適合網路和行動應用程式的互動式且具有視覺吸引力的圖形和圖表。 https://github.com/plotly/plotly.py Star ⭐ Plotly 儲存庫 --- 21. **Nltk** ------------ 該庫使自然語言處理變得易於存取且易於使用。 https://github.com/nltk/nltk Star ⭐ Nltk 儲存庫 --- 22.**SpaCy** ---------- 提供工業級自然語言處理能力以及針對多種語言的預訓練模型。 https://github.com/explosion/spaCy Star ⭐ SpaCy 儲存庫 --- **23.Gensim** ------------- 專注於無監督主題建模和自然語言處理,您可以使用該程式庫來分析文件相似性。 https://github.com/RaRe-Technologies/gensim Star ⭐ Gensim 儲存庫 --- 24.Py**Test** ----------- 一個強大的框架,用於編寫小型到複雜的功能測試,增強測試的可讀性和可維護性。 https://github.com/pytest-dev/pytest Star ⭐ PyTest 儲存庫 --- 25.**單元測試** ----------- 用於建置和執行測試的內建框架,反映了其他語言中的 xUnit 架構。 Unitest 是內建的。 --- 26.**Fabric** --------- 簡化應用程式部署或系統管理任務的 SSH,自動執行遠端 shell 命令。 https://github.com/fabric/fabric Star ⭐ Fabric 儲存庫 --- 27.**Vizzu** -------- Vizzu 旨在動畫資料視覺化和講故事,是建立動態和互動式圖表的首選庫。 https://github.com/vizzuhq/vizzu-lib Star ⭐ Vizzu 儲存庫 --- 28.**Polars** --------- 針對效能和效率進行最佳化的 DataFrame 庫,能夠輕鬆處理大型資料集。 https://github.com/pola-rs/polars Star ⭐ Polars 儲存庫 --- 29.Docker **-Py** ----------------- 提供對 Docker Remote API 的 Pythonic 存取,從而實現 Docker 容器管理的自動化。 https://github.com/docker/docker-py Star ⭐ Docker-Py 儲存庫 --- **30.OpenCV** ------------- 電腦視覺和影像處理的主要內容,提供一整套演算法和工具。 https://github.com/opencv/opencv Star ⭐ OpenCV 儲存庫 --- 31.Scikit**-image** --------------- 它致力於影像處理,將 SciPy 和 NumPy 的功能擴展到視覺領域。 https://github.com/scikit-image/scikit-image Star ⭐ Scikit-image 儲存庫 --- 32.**SymPy** --------- 該庫專為符號計算而設計,提供從代數求解到微積分的各種功能。 https://github.com/sympy/sympy Star ⭐ SymPy 儲存庫 --- 33.**Virtualenv** ----------- 對於建立隔離的 Python 環境和乾淨地管理專案依賴至關重要。 https://github.com/pypa/virtualenv Star ⭐ Virtualenv 儲存庫 --- 34.**Click** --------- 簡化命令列介面的建立,促進可組合且易於擴展的程式碼。 https://github.com/pallets/click 為 Click 儲存庫加註星標 --- 35. **argparse** ---------------- 促進命令列參數的解析,這對於 CLI 應用程式開發至關重要。 Argparse 是內建的。 --- 36.**日誌記錄** ----------- 提供靈活的日誌記錄系統,從簡單的日誌記錄到複雜的每個模組配置。 日誌記錄是內建的。 --- **37.PyYAML** ------------- 處理 YAML 文件,支援 Python 物件與 YAML 之間的序列化和反序列化。 https://github.com/yaml/pyyaml Star ⭐ PyYAML 儲存庫 --- 38.xlrd **/xlwt** ----------------- 非常適合讀取和寫入 Excel 文件,彌補了 Python 和 Excel 文件之間的差距。 https://github.com/python-excel/xlrd Star ⭐ xlrd 儲存庫 https://github.com/python-excel/xlwt Star ⭐ xlwt 儲存庫 --- 39. **Pandas 分析** ----------------- 從 pandas 產生全面的配置文件報告 https://github.com/pandas-profiling/pandas-profiling Star ⭐ Pandas-Profiling 儲存庫 --- 40.**全面品質管理** ------------- Tqdm 是任何循環的包裝器,它將透過進度條追蹤進度。 https://github.com/tqdm/tqdm Star ⭐ TQDM 儲存庫 --- 41.**Faker** --------- 需要看起來真實的假資料嗎? Faker 為你提供支援。 https://github.com/joke2k/faker Star ⭐ Faker 儲存庫 --- 42.**Flake8** ---------- 一個必備的庫,可以使您的程式碼保持簡潔,並輕鬆實現樣式檢查。 https://github.com/PyCQA/flake8 Star ⭐ Flake8 儲存庫 --- 43.**Black** --------- 將您的程式碼格式提升到一個新的水平。 https://github.com/psf/black Star ⭐ Black 儲存庫 --- 44.**Mypy** ---------- 這就像有一位文法老師來教你的程式碼,但教你的類型。 https://github.com/python/mypy Star ⭐ Mypy 儲存庫 --- 45.**Pydantic** ----------- 驗證 Python 腳本所需的函式庫。 https://github.com/samuelcolvin/pydantic Star ⭐ Pydantic 儲存庫 --- **46.FastAPI** -------------- FastAPI 是一個用於建立 RESTful API 的 Web 框架。 https://github.com/tiangolo/fastapi Star ⭐ FastAPI 儲存庫 --- 47.**Catboost** ---------- 為您的機器學習模型提供處理分類資料的方法。 https://github.com/catboost/catboost Star ⭐ Catboost 儲存庫 --- 48.**Seaborn** ---------- 提高資料可視化水準。 https://github.com/mwaskom/seaborn Star ⭐ Seaborn 儲存庫 --- 49.**Turtle graphics ** --------- 透過酷炫的圖形和動畫將程式設計帶入生活。學習並開始使用 Python 的好方法。 Turtle graphics 是內建的。 --- 50.**Asciimatics** ------------ Asciimatics 是一個可讓您建立全螢幕文字 UI 的程式庫。 https://github.com/peterbrittain/asciimatics Star ⭐ Asciimatics 儲存庫 --- 原文出處:https://dev.to/taipy/python-libraries-you-need-to-know-in-2024-37ka

在各種部落格平台,放進自己的的程式碼

在本文中,我將概述各種[部落格平台及其程式碼注入功能](https://bloggingplatforms.app/blog/blogging-platforms-with-the-best-code-injection)。 想像自己是個博主,無論您是經驗豐富還是剛起步;你不僅僅是一個文字大師。您擁有 Web 開發技能,並且渴望控制線上主頁的外觀、感覺和功能。這就是部落格平台上的程式碼注入可以發揮作用的地方! 我將指導您使用[最好的部落格平台](https://bloggingplatforms.app/)來注入自訂程式碼。 **為什麼程式碼注入很重要以及它如何使您受益** 讓我們分解一下:程式碼注入意味著在您的部落格中加入自訂程式碼(如 HTML、CSS 或 JavaScript)。此功能很有用,因為: - **獨特的設計:**擺脫模板並個性化您部落格的視覺效果。 - **特殊功能:**考慮互動式元素、自訂小工具或獨特的動畫。 - **資料追蹤:**整合您喜歡的分析工具以獲得深入的見解。 - **功能改進:**優化頁面載入速度或實現複雜功能。 ![為部落格平台注入程式碼的好處](https://bloggingplatforms.app/media/posts/blogging-platforms-with-the-best-code-injection/benefits-of-code-injection.webp) **具有最佳程式碼注入選項的 Bogging 平台** --------------------------- ### **WordPress:程式碼注入動力源** 作為內容管理系統 (CMS) 領域無可爭議的皇帝, [WordPress](https://wordpress.com/)擁有無與倫比的程式碼注入能力。 其**主題自訂**功能可讓您直接存取主題文件,使您能夠透過主題編輯器無縫整合自訂程式碼片段。 此外,**程式碼片段**和**插入頁首和頁尾等**[WordPress 外掛](https://wordpress.com/plugins)提供了使用者友善的介面,用於將程式碼注入部落格佈局的特定部分,例如頁首、頁尾或側邊欄。 #### **探索 WordPress 的程式碼注入功能:** - **主題編輯:**對於技術嫻熟的人來說,WordPress 透過內建主題編輯器授予對主題文件的完全存取權。這種精細的控制使您能夠將程式碼直接注入到模板檔案(header.php、footer.php 等)中,從而對部落格的佈局和功能進行深度自訂。 - **外掛程式:**廣泛的 WordPress 外掛程式生態系統提供了大量的程式碼注入工具。程式碼片段和插入頁首和頁尾等插件提供了用戶友好的介面,用於將程式碼片段注入部落格的特定區域,滿足所有技術背景的用戶的需求。這些插件通常配備程式碼語法突出顯示和錯誤檢查等功能,從而簡化程式碼注入過程。 #### **重要考慮因素:** - **主題相容性:**直接注入主題檔案的程式碼本質上連結到您正在使用的特定主題。如果切換主題,您可能需要修改或重新註入程式碼片段。 - **插件依賴:**雖然插件簡化了程式碼注入,但它們引入了外部依賴項。確保您選擇的外掛程式得到積極維護並與您的 WordPress 版本相容。 --- ### **Webflow:透過視覺編碼為精通設計的部落客提供支持** [Webflow](https://webflow.grsm.io/gr15bvbdlvfo)提出了一個獨特的主張:一個**視覺化開發平台**,讓您無需編寫任何程式碼即可建立自訂網站。正因為如此,Webflow 是[藝術家最好的部落格平台](https://bloggingplatforms.app/blog/best-blog-platforms-for-artists)之一。 然而,對於那些尋求更精細控制的人來說, [Webflow](https://webflow.grsm.io/gr15bvbdlvfo)提供了一個程式碼注入功能,恰當地命名為**「自訂程式碼」** 。此功能可讓您將程式碼片段直接注入網站的專案設定中,從而可以微調特定的設計元素和功能。 #### **釋放 Webflow 的程式碼注入潛力:** - **自訂程式碼:** Webflow 的自訂程式碼功能可讓您存取專案設定中指定的程式碼注入區域。在這裡,您可以注入針對網站設計和功能的特定方面的程式碼片段,例如加入自訂動畫、整合第三方服務或修改現有元素的行為。 - **Visual Canvas:** Webflow 的主要優點在於其視覺化開發介面。您無需直接操作程式碼即可實現顯著程度的自訂。然而,自訂程式碼為那些尋求更深入研究並釋放程式碼注入全部威力的人提供了一個逃生口。 #### **重要考慮因素:** - **學習曲線:**雖然 Webflow 提供了視覺化開發介面,但了解基本的 HTML、CSS 和 JavaScript 對於有效的程式碼注入非常有益。 - **範圍有限:**與 WordPress 等成熟的 CMS 相比,Webflow 的程式碼注入功能旨在微調設計元素和功能,而不是進行廣泛的結構修改。 --- ### **WebWave:為新手部落客簡化程式碼注入** [WebWave](https://webwave.me/ref/14072231082)是另一個視覺化網站建立器,它迎合了那些在用戶友好的拖放功能和注入自訂程式碼的能力之間尋求平衡的人。其**程式碼編輯器**可讓您將程式碼片段注入網站佈局的特定部分,從而提供個人化的途徑,而無需廣泛的編碼專業知識。 **探索 WebWave 的程式碼注入功能:** - **程式碼編輯器:** WebWave 的程式碼編輯器可讓您將程式碼片段直接注入網站頁面的指定部分。這種有針對性的方法可讓您自訂特定元素,例如新增自訂按鈕、整合小工具或修改現有功能。 - **初學者友善的介面:**程式碼編輯器提供了一個相對用戶友好的介面,具有語法突出顯示和基本的錯誤檢查功能,即使對 Web 開發有基本了解的部落客也可以使用它。 #### **重要考慮因素:** - **範圍有限:** WebWave 的程式碼注入功能著重於在地化修改,而不是對網站進行全面的結構變更。 - **外部依賴:**依賴 WebWave 的程式碼編輯器意味著一定程度的平台鎖定。如果您要遷移網站,自訂程式碼片段可能需要修改。 --- ### **Typedream:無程式碼環境中的程式碼注入** [Typedream](https://typedream.com/?via=blogplatforms)將自己定位為無程式碼網站建立器,在建立精美網站時優先考慮易用性。然而,它提供了有針對性的程式碼注入功能來擴展其功能並允許超出預定模板的自訂。 #### **Typedream 的程式碼注入潛力:** - **嵌入元素:**透過嵌入程式碼片段,將第三方服務、小工具或自訂元素整合到 Typedream 網站的特定區域。 - **功能增強:**透過自訂互動、動畫或獨特的視覺效果擴展 Typedream 的內建功能。 #### **重要考慮因素:** - **無程式碼優先:** Typedream 的優勢在於其簡單性和使用者友善性。程式碼注入可作為高級使用者工具使用,而不是其主要的客製化方法。 --- ### **Unicorn:程式碼注入以實現靈活性** [Unicorn Platform](https://unicornplatform.com/?via=bloggingplatforms)透過其拖放介面簡化了網站開發流程。此外,它還提供**程式碼注入**功能,可讓您透過將程式碼片段直接插入特定部分來進一步自訂您的網站。 #### **Unicorn 的程式碼注入潛力:** - **有針對性的客製化:** Unicorn 的程式碼注入功能可讓您修改單一元件或為您的網站加入新功能。整合第三方服務、建立自訂動畫或根據需要調整樣式。 - **使用者友善的介面:** Unicorn 對簡單性的關注延伸到了其程式碼注入功能,使其對於具有基本 Web 開發知識的使用者來說易於使用。 #### 重要考慮因素: - **平台依賴:**請記住,注入 Unicorn 的自訂程式碼片段依賴於平台。如果您決定遷移站點,程式碼相容性可能會成為一個問題。 --- ### **Dorik:無程式碼,但具有客製化潛力** [Dorik](https://dorik.com/?ref=can-burak72)將自己定位為專注於無程式碼原則的未來網站建立者。它的目的是擺脫傳統的頁面建立器。雖然 Dorik 並沒有專注於程式碼注入,但它在其新穎的框架中提供了客製化潛力。 #### **Dorik 的客製化潛力:** - **程式碼探索:**期望在 Dorik 上採用更具實驗性的客製化方法,可能涉及獨特的視覺化工具,而不是直接程式碼注入。 #### **重要考慮因素:** - **不斷發展的平台:** Dorik 相對較新,因此其客製化理念可能會隨著時間的推移而不斷發展。隨時了解他們的發展路線圖以獲取更多見解。 --- ### **Wix:用於擴展功能的程式碼注入** [Wix](https://www.wix.com/)是一種流行的拖放式網站建立器,透過其開發人員工具集(稱為**Corvid by Wix(以前稱為 Velo))**提供程式碼注入功能。這個先進的平台使您能夠透過編寫自訂 JavaScript 程式碼和整合外部 API 來擴展 Wix 網站的功能。 #### **利用 Corvid(以前稱為 Velo)的力量:** - **以 JavaScript 為中心:** Corvid 主要依賴 JavaScript 來實作自訂功能。對 JavaScript 的深入理解對於充分發揮其潛力至關重要。 - **API 整合:** Corvid 可以整合第三方服務和 API,從而增強您網站的功能,超越 Wix 內建工具的限制。 - **專用開發環境:**存取 Corvid 需要轉向專用開發環境,這可能會為非程式設計師帶來更陡峭的學習曲線。 #### **重要考慮因素:** - **陡峭的學習曲線:**有效利用 Corvid 需要 JavaScript 的應用知識和熟悉程式設計概念。 - **Wix 生態系內的有限控制:雖然很靈活,但 Corvid 的功能僅限於 Wix 生態系的範圍內。**廣泛的網站結構修改可能會受到限制。 --- ### **Squarespace:在易用性和客製化之間取得平衡** [Squarespace](https://www.squarespace.com/)以其用戶友好的介面和拖放功能而聞名,提供了一種經過衡量的程式碼注入方法。其**程式碼注入**功能可讓您將程式碼片段插入網站的指定區域,從而無需具備豐富的編碼知識即可實現有針對性的自訂。 #### **釋放 Squarespace 的程式碼注入潛力:** - **有針對性的客製化:** Squarespace 的程式碼注入功能適合特定的修改。嵌入自訂字體、整合社交媒體來源或加入自訂按鈕來增強部落格的外觀和感覺。 - **初學者友善的介面:** Squarespace 的程式碼注入功能優先考慮可存取性。即使具有最少編碼經驗的使用者也可以導航介面並實現基本的程式碼修改。 #### **重要考慮因素:** - **範圍有限:** Squarespace 的程式碼注入主要專注於在地化自訂,而不是對網站進行徹底的結構變更。 - **平台依賴:**注入 Squarespace 的自訂程式碼片段與平台相關。如果您要遷移網站,程式碼相容性可能會成為問題。 --- ### **Pixpa:攝影師和創意人員的程式碼注入** [Pixpa](https://www.pixpa.com/signup?refcode=BURAK10)專門為尋求展示作品平台的攝影師和創意專業人士提供服務。雖然其核心功能圍繞著令人驚嘆的視覺效果,但 Pixpa 為尋求額外控制的人提供了**程式碼注入**功能。 #### **Pixpa 的程式碼注入功能:** - **增強的功能:**注入程式碼片段以整合第三方服務,例如分析工具、支付網關或自訂聯絡表單,從而擴展部落格的功能。 - **易於使用:** Pixpa 的程式碼注入功能提供了使用者友善的介面和清晰的說明,使得非程式設計師也可以輕鬆使用。 #### **重要考慮因素:** - **有限的客製化:** Pixpa 的程式碼注入主要針對功能增強而不是廣泛的設計修改。 - **專注於利基市場:**雖然 Pixpa 非常適合創意人士,但它可能無法像更通用的平台那樣有效地迎合所有部落格利基市場。 --- ### **PageCloud:用於有針對性的增強的程式碼注入** [PageCloud](https://www.pagecloud.com/home-partners?gspk=Y2FuYnVyYWtzb2Z5YWxpb2dsdTMwNTQ&gsxid=Is2tDreeXpFm&utm_campaign=affiliate-referral-program&utm_medium=partner&utm_source=canburaksofyalioglu3054)將自己定位為具有程式碼注入功能的用戶友好的網站建立器。其**自訂程式碼**功能可讓您將程式碼片段注入網站的特定部分,從而實現有針對性的自訂。 #### **探索 PageCloud 的程式碼注入選項:** - **特定部分:** PageCloud 的程式碼注入著重於修改網站的指定部分,例如頁首、頁尾或側邊欄。這種方法非常適合整合小部件、加入自訂按鈕或微調佈局。 - **初學者的介面:** PageCloud 透過其程式碼注入功能優先考慮易用性。清晰的說明和用戶友好的介面使得那些具有最少編碼經驗的人也可以使用它。 #### **重要考慮因素:** - **範圍有限:**與 Squarespace 類似,PageCloud 的程式碼注入功能面向局部增強,而不是廣泛的結構修改。 - **平台依賴性:**自訂程式碼片段依賴PageCloud。從平台遷移可能需要程式碼調整或重新註入。然而,這可以被視為 PageCloud 提供的易用性和用戶友好介面的權衡。 --- ### **Blogger:具有基本程式碼注入功能的免費平台** [Blogger](https://www.blogger.com/)上提供了基本等級的程式碼注入功能,Blogger 是 Google 的免費部落格平台。透過其**HTML/CSS 編輯**功能,您可以存取和修改部落格範本的底層程式碼。 #### **Blogger 的程式碼注入潛力:** - **直接模板編輯:**對於熟悉程式碼的人,Blogger 授予對其模板文件的存取權限,從而可以直接修改控制部落格佈局和樣式的 HTML 和 CSS 程式碼。 - **功能有限:** Blogger 的程式碼注入功能是針對基本自訂,主要涉及編輯現有程式碼,而不是注入全新的功能。 #### **重要考慮因素:** - **所需技術專長:**直接模板編輯需要對 HTML 和 CSS 有深入的了解。對於初學者來說,這種方法可以呈現更陡峭的學習曲線。 - **控制有限:**與付費平台相比,Blogger 的免費方案對客製化施加了限制。 --- ### **Framer:為 Web 開發人員提供程式碼驅動的客製化** [Framer](https://www.framer.com/)是一個強大的視覺設計平台,整合了 React 編碼功能,為 Web 開發人員提供了一個遊樂場。雖然 Framer 主要針對應用程式開發,但其以程式碼為中心的方法為在其生態系統中建立部落格的人員提供了廣泛的客製化可能性。 #### **探索 Framer 的程式碼注入功能:** - **以開發人員為中心的客製化:**使用 Framer,您基本上可以使用 React 元件建立博客,從而可以對從佈局到互動的各個方面進行細粒度控制。 - **無限的可能性:** Framer 的程式碼注入幾乎是無限的,使您能夠製作一個突破傳統設計和功能界限的部落格。 #### **重要考慮因素:** - **陡峭的學習曲線:**有效利用 Framer 需要對 React 和 Web 開發原理有深入的了解。 - **資源密集:**與程式碼密集度較低的平台相比,在 Framer 中開發部落格可能需要更多時間和開發資源。 --- ### **Ghost:為精通程式碼的用戶提供開源靈活性** [Ghost](https://ghost.org/)以專注於純粹的部落格而聞名,提供了對開發人員有吸引力的開源靈活性。其主題結構利用 Handlebars 模板語言,允許全面的程式碼注入和客製化。 #### **Ghost的程式碼注入潛力:** - **完整的主題自訂:** Ghost 的開源特性可讓您直接修改主題文件,從而對部落格的結構和設計提供高階的控制。 - **社區驅動的支持:** Ghost 受益於蓬勃發展的開發者社區,該社區共享主題、程式碼片段和知識,培育了豐富的生態系統。 #### **重要考慮因素:** - **技術專長:** Ghost 中的有效程式碼注入需要熟悉 Handlebars 範本和 Web 開發原則。 - **自架:**為了實現完全客製化的潛力,自架您的 Ghost 部落格可能是必要的,這會帶來額外的技術開銷。 --- ### **曝光:攝影師的程式碼注入** [Exposure](https://exposure.co/)專注於視覺敘事,並擁有時尚的介面。它使攝影師和那些有視覺傾向的人能夠建立令人驚嘆的部落格來展示他們的作品。 Exposure 提供了注入自訂程式碼的能力,為進一步個性化您的線上形像打開了大門。 #### **了解 Exposure 的程式碼注入功能:** - **有針對性的調整:**將自訂程式碼注入您的 Exposure 部落格的特定區域,例如頁首、頁尾或單一頁面。 - **功能增強:**透過整合第三方工具或自訂元素來增強您的博客,擴展 Exposure 的內建功能。 #### **重要考慮因素:** - **社群支援:**考慮專門為 Exposure 上的程式碼注入量身定制的資源的可用性,因為其社群可能比某些其他平台小。 --- ### **Hashnode:為開發者部落客客製化的程式碼注入解決方案** [Hashnode](https://hashnode.com/)是一個為開發人員量身定制的社群驅動的部落格平台。它是[**最好的開發者部落格平台**](https://bloggingplatforms.app/blog/best-blogging-platforms-for-developers)之一。 它優先考慮技術討論和知識共享。使用 Hashnode,您可以注入自訂程式碼來客製化部落格的外觀和功能。 #### **探索Hashnode的程式碼注入功能:** - **自訂樣式:**使用自訂 CSS 程式碼修改 Hashnode 部落格的外觀,創造與您的品牌相符的獨特外觀。 - **嵌入和小部件:**整合程式碼片段以顯示程式碼區塊、可嵌入內容和動態小部件,豐富您的技術寫作。 #### **重要考慮因素:** - **利基焦點:** Hashnode 最適合開發人員和技術部落客。它可能不是一般興趣部落格的理想平台。 --- ### **Odoo:模組化 CMS 中的程式碼注入** [Odoo](https://www.odoo.com/)是一個龐大的開源業務管理套件,包括網站建立器和部落格模組。它提供了注入程式碼的能力,允許在 Odoo 生態系統中進行客製化。 #### **Odoo 的程式碼注入潛力:** - **深度整合:**自訂 Odoo 模組(包括您的部落格)以與特定業務工作流程或流程保持一致。 - **框架熟悉度:** Odoo 中的有效程式碼注入需要了解其基於 Python 的開發框架。 **重要考慮因素:** - **以企業為中心:** Odoo 的複雜性使其最適合擁有大量 IT 資源的企業,而不是個人部落客。 --- ### **Jimdo:有限的程式碼注入** [Jimdo](https://www.jimdo.com/)是一個用戶友好的網站建立器,提供有限程度的程式碼注入。您可以將基本 HTML 片段新增至網站的某些區域。 #### **重要考慮因素:** - **簡單性:** Jimdo 優先考慮易用性而不是廣泛的客製化選項。 - **最適合初學者:** Jimdo 上的程式碼注入可能適合簡單的修改,但無法滿足需要高級自訂的用戶的需求。 --- ### **Weebly:用於基本客製化的定向程式碼注入** [Weebly](https://www.weebly.com/)是另一個受歡迎的拖放網站建立器,提供有針對性的程式碼注入功能。其**嵌入程式碼**功能可讓您將 HTML 和 JavaScript 片段插入網站的特定部分,從而實現基本的修改和整合。 #### **Weebly 的程式碼注入潛力:** - **具體增強功能:**利用 Weebly 的程式碼注入來整合第三方小工具,例如社群媒體來源或即時聊天工具。 - **適合初學者:** Weebly 的嵌入程式碼功能為基本程式碼插入提供了一個簡單的介面。 #### **重要考慮因素:** - **Weebly 的程式碼注入範圍:**與 Squarespace 和 PageCloud 一樣,Weebly 的程式碼注入專注於局部增強而不是廣泛的結構變化。 - **平台相容性:**注入 Weebly 的自訂程式碼與平台綁定。遷移可能需要程式碼調整或重新註入。 --- ### **Tumblr:主題客製化的程式碼注入** [Tumblr](https://www.tumblr.com/)是一個以其強大的社群和社交功能而聞名的微博平台,允許透過其主題自訂選項進行一定程度的程式碼注入。 #### **Tumblr 的程式碼注入潛力:** - **主題修改:**直接存取主題檔案可讓您注入 HTML、CSS 和 JavaScript 程式碼。自訂 Tumblr 部落格的佈局、樣式和功能。 - **創意人員的靈活性:** Tumblr 的開放主題結構和對視覺表達的重視使其成為渴望獨特線上形象的創意人士的熱門選擇。 #### **重要考慮因素:** - **熟悉語法:**修改 Tumblr 主題需要對 HTML、CSS 和 JavaScript 語法有基本的了解。 - **社群驅動:** Tumblr 擁有龐大的主題開發人員社區,他們經常分享程式碼片段和自訂技巧。 --- ### **Tilda:帶有程式碼注入選項的視覺設計** [Tilda](https://tilda.cc/)是一個強調設計的模組化網站建立器,在其**零區塊**功能中提供程式碼注入功能。此功能可讓您插入自訂程式碼,提供超越其視覺化建構器工具的靈活性。 #### **Tilda 的程式碼注入潛力:** - **視覺 + 程式碼:**在 Tilda 直覺的拖放介面和程式碼注入的強大功能之間取得平衡。建立獨特的元素或修改現有區塊以進行細粒度控制。 - **有針對性的增強:**透過整合、自訂動畫或獨特的設計元素擴展 Tilda 的功能。 #### **重要考慮因素:** - **零塊特定:** Tilda 上的程式碼注入主要側重於零塊功能內的自定義,與直接主題編輯相比,提供了更結構化的方法。 - **設計優先:Tilda 專注於將拖放建構器作為主要設計工具。**程式碼注入是擴展定制的一個有價值的補充功能。 --- ### **SmugMug:針對以視覺為中心的攝影師的有限程式碼注入** [SmugMug](https://www.smugmug.com/)是一個專門為攝影師展示和銷售作品而設計的平台。它提供有限的程式碼注入功能,主要用於基本修改。 #### **SmugMug 的程式碼注入潛力:** - **有限制的自訂:**雖然 SmugMug 允許進行一些 HTML 和 CSS 自訂,但其主要重點是視覺驅動的模板和主題。 - **適合攝影師:** SmugMug 的核心受眾可能會發現程式碼注入不再那麼重要,因為該平台優先考慮易用性來展示令人驚嘆的視覺效果。 #### **重要考慮因素:** - **特定領域:** SmugMug 非常注重影像展示和銷售功能,為攝影師提供了良好的服務。對於 SmugMug 的核心用戶來說,大量的程式碼注入可能不是優先考慮的事情。 --- ### **Cargo:創意組合的程式碼注入** [Cargo](https://cargo.site/)以其極簡設計和強調展示創意作品而聞名,允許一定程度的程式碼注入。此功能使用戶能夠在預先建立的模板之外個性化他們的線上作品集。 #### **Cargo 的程式碼注入潛力:** - **有針對性的自訂:**注入程式碼片段可以進行自訂,例如自訂字體、獨特的佈局或互動式元素,以增強您的創意作品的呈現。 #### **重要考慮因素:** - **範圍有限:** Cargo 上的程式碼注入最適合在地化增強,而不是對您的產品組合進行徹底的結構性變更。 --- ### **Adobe Portfolio:為視覺藝術家提供有限的程式碼注入** [Adobe Portfolio](https://portfolio.adobe.com/)與 Adobe 的 Creative Cloud 套件集成,主要專注於視覺作品集的無縫展示。它提供有限的程式碼注入功能,通常用於較小的樣式調整或嵌入第三方內容。 #### **Adobe Portfolio 的程式碼注入潛力:** - **增強視覺效果:**利用程式碼注入來自訂工作的呈現、加入微妙的動畫或嵌入互動元素。 - **專注於集成:** Adobe Portfolio 優先考慮與其他 Adobe Creative Cloud 服務的集成,而不是廣泛的程式碼驅動自訂。 #### **重要考慮因素:** - **視覺第一:** Adobe Portfolio 的核心優勢在於其易用性和專注於令人驚嘆的視覺呈現。程式碼注入能力是次要的。 --- ### **Vev:平衡視覺設計與程式碼注入** [Vev](https://www.vev.design/?gspk=Y2FuYnVyYWtzb2Z5YWxpb2dsdTMwNTQ&gsxid=6ql2Ybh49e9T&utm_campaign=affiliate&utm_id=VevPartners&utm_medium=partnerstack&utm_source=partnerstack)在直覺的視覺化設計工具和程式碼注入的靈活性之間提供了平衡。其專用的程式碼注入區域可實現有針對性的客製化和整合。 #### **Vev 的程式碼注入潛力:** - **自訂元素:**在 Vev 視覺建構器的框架內建立獨特的元素或修改現有元素,以獲得客製化的外觀和感覺。 - **第三方整合:**透過使用程式碼無縫整合外部服務和小部件來擴展部落格的功能。 #### **重要考慮因素:** - **混合方法:** Vev 迎合了既尋求視覺化建構器的便利性又尋求目標程式碼注入修改的強大功能的使用者。 --- ### **Voog:高級客製化的程式碼注入** [Voog](https://www.voog.com/)是一個多語言網站建立器,為開發人員和尋求對其網站結構和設計進行廣泛控制的人員提供強大的程式碼注入功能。 #### **Voog 的程式碼注入潛力:** - **完整的主題控制:** Voog 的開放式結構允許直接修改主題文件,從而實現廣泛的客製化可能性。 - **API 整合:**利用 Voog 的 API 整合自訂功能並簡化工作流程。 #### **重要考慮因素:** - **技術專長:**在 Voog 中進行有效的程式碼注入需要熟悉 Web 開發原理。 - **多語言聚焦:** Voog 的優勢在於其多語言能力。如果這是一個核心需求,那麼它的程式碼注入潛力就變得特別有利。 --- ### 格式:投資組合網站的有限程式碼注入 [Format](https://format.grsm.io/vdptwrg0w0q9)迎合了尋求透過令人驚嘆的作品集網站展示其作品的創意人士。它提供一定程度的程式碼注入,但優先考慮簡單性和視覺化設計工具。 #### Format 的程式碼注入潛力: - **整合與增強:**注入程式碼以嵌入外部內容、追蹤分析或為您的產品組合加入微妙的自訂。 #### 重要考慮因素: - **視覺焦點:**與 Ghost 或 WordPress 等平台相比,Format 的體驗不太以程式碼為中心。程式碼注入主要作為補充選項。 --- ### Carbonmade:用於組合定制的程式碼注入 [Carbonmade](https://carbonmade.com/)與 Format 和 Adobe Portfolio 類似,專為建立線上作品集的創意人員量身定制。它提供了適合基本修改和增強的程式碼注入等級。 #### Carbonmade 的程式碼注入潛力: - **微調示範:**透過 CSS 調整和基於 JavaScript 的互動來自訂 Carbonmade 產品組合的外觀和感覺。 #### 重要考慮因素: - **產品組合特定:** Carbonmade 的程式碼注入功能可能無法提供與 WordPress 等成熟的 CMS 相同的深度。 ### **結論** 選擇正確的具有程式碼注入的部落格平台可以歸結為在客製化和易用性之間取得平衡。請記住,您理想的部落格平台取決於您的具體需求、技術專長以及您對線上空間的創意願景。 --- 原文出處:https://dev.to/elastoplastique/code-injection-options-for-blogging-platforms-2g0a

Snake...純 HTML⁉️ [沒有 JS,沒有 CSS,沒有圖片!!] 😱

他們說有些人就是喜歡混亂。 大家好👋🏼,我是格雷厄姆「喜歡混亂」TheDev,這次我帶著另一個愚蠢的網路實驗回來了(如果你願意,你可以[直接跳到遊戲](#the-game))。 一切都是那麼天真地開始,「我可以寫一個貪吃蛇遊戲嗎?」。 但是,一如既往,我肩膀上的小惡魔低聲說「讓它變得更難」......所以我想「沒有 JavaScript,用純 CSS 來做」。 他再次嘰嘰喳喳地說:「噗,還是太簡單了,而且你最近做了太多 CSS 東西,用原始的、無樣式的 HTML 來做吧」。 我轉向另一邊肩膀,想聽聽天使的想法,希望得到更明智的結果。 然後我想起天使從來沒有在我身邊... 所以這就是,snake,純 HTML 格式(用一點 PHP 技巧來支援它)。 這是正確的! - 沒有 JavaScript - 沒有圖片 - 沒有CSS - 沒有 Cookie 不過,我想澄清一下(因為我不想被指責為點擊誘餌),我正在使用 PHP 渲染此 HTML。 雖然可以僅使用文件以純 HTML 形式完成此操作,無需後端語言,但它需要 640,345,228,142,352,307,046,244,325,015,114,448,670,890, 662,773,914,918,117,331,955,996,440,709,549,671,345,290,477,020,322,434,911,210,797,593,280,795,101, 545,372,667,251,627,877,890,009,349,763,765,710,326,350,331,533,965,349,868,386,831,339,352,024,373, 788,157,786,791,506,311,858,702,618,270,169,819,740,062,983,025,308,591,298,346,162,272,304,558,339, 520,759,611,505,302,236,086,810,433,297,255,194,852,674,432,232,438,669,948,422,404,232,599,805,551,610,635,942,376,961,399 ,231,917,134,063,858,996,537,970,147,827,206,606,320,217,379,472,010,321,356,624,613,809,077,942,304,597,360,699,567,595,836, 096,158,715,129,913,822,286,578,579,549,361,617,654,480,453,222,007,825,818,400,848,436,415,591,229,454,275,384,803,558,374,5 18,022,675,900,061,399,560,145,595,206,127,211,192,918,105,032,491,008,000,000,000,000,000,000,000,000,000,000,000,000,000,00 0,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000 個文件。 所以請原諒使用 PHP 產生下一頁的「捷徑」(對於那些在技術 Twitter 上花費太多時間的人,也請原諒我使用「死」語言!😱🤣)。 不管怎樣,序言太多了,我知道你為什麼來這裡,你想看到它的實際效果! 玩 HTML 貪吃蛇(有警告!) ---------------- 在桌面 PC 上的 Chrome 上執行...對於我來說,在 Firefox 和 iOS 上的任何瀏覽器上執行速度太快...您將在本文後面了解原因。 所以基本上,在桌面版 Chrome 中玩吧! 關鍵是: - ALT + I向上, - ALT + J向左, - ALT + K向下, - ALT + L向右, - ALT + O開始新遊戲(一旦你輸了)。 在 Mac 上,我相信是Control + Option而不是Alt ! 如果你想知道為什麼奇怪的鍵而不是 WASD,不幸的是ALT + D已經在 Windows 上的 Chrome 中使用,所以我不得不選擇「安全」鍵。 **最後一個警告:**我們用於實現此功能的技巧之一會用大量 URL 淹沒您的瀏覽器歷史記錄...您已被警告! ### 遊戲 **遺憾的是,這無法在 codepen 中執行,因此您必須[在我的網站上玩 HTML Snake](https://grahamthe.dev/demos/snake/) 。** 當你玩完後,回來看看我用了什麼技巧來完成這個工作(並在評論中分享你的最高分!)。 問題 1:取得遊戲勾選 ----------- 對於遊戲,您*通常*需要有一個“遊戲勾選”。每個刻度是當一個動作發生或您計算一個新的遊戲狀態然後渲染新的遊戲狀態。 但這提出了我們的第一個問題,我們如何能夠在沒有 JavaScript 的情況下自動更新頁面? 嗯,在 HTML 中執行此操作實際上非常簡單,我們只需將[`<meta http-equiv="refresh"`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#http-equiv)設為較低值即可。 因此,我們從 0.35 秒刷新時間開始,然後隨著您的分數攀升,將刷新時間加快至 0.2 秒。 「元刷新」允許我們做的是指示瀏覽器載入頁面的 HTML 後,等待 X 秒,然後載入另一個 URL。 透過設定較低的刷新時間,然後更改我們在每次刷新時重定向到的 URL(稍後會詳細介紹),我們有一種方法可以讓頁面自行更改,即使您不按任何按鈕! 以下是格式的簡單範例: ``` <meta http-equiv="refresh" content="[time];url=[url-to-redirect-to]"> ``` **附註:**這是我之前提到的它不適用於其他瀏覽器的地方。他們不排除部分第二次刷新時間,因此刷新是即時的,使得遊戲太快而無法玩。 但僅元刷新不足以使遊戲正常執行,我們需要某種方法來保存遊戲狀態並將蛇方向的變化傳達給伺服器。 為此,我們使用另一個直接的技巧:URL 編碼的 GET 參數。 問題 2:管理遊戲狀態 ----------- 因為我們不能使用 POST 請求或類似的東西,所以我們需要另一個機制來管理瀏覽器和伺服器之間的遊戲狀態。 起初,我使用多個 GET 參數來管理狀態,因此 URL 如下所示: ``` url?playing=1&x=2&y=6&foodx=3&foody=6&dir=left. ``` 這一直工作得很好,直到我需要為蛇儲存多個點(它佔據的每個方塊的 x,y 座標)。 雖然我確實讓它與一些 hacky x,y 座標列表和解析一起工作(例如`snake=1,1,2,1` ,蛇位於x=1,y=1 和x=2,y=1),但這是凌亂的。 因此,我們轉向我們的好朋友: [`urlencode()`](https://www.php.net/manual/en/function.urlencode.php)和[`json_encode()`](https://www.php.net/manual/en/function.json-encode.php) 。 一起使用時,我可以取得一個陣列(或在本例中為多維陣列),將其轉換為 JSON,然後將其轉換為 URL 的有效字元。 讓我解釋: ### 在 URL 中儲存複雜資料 以下是我用於遊戲狀態的資料範例: ``` $state = array( 'width' => $width, 'height' => $height, 'snake' => array(array('x' => 5, 'y' => 5)), 'food' => array('x' => 7, 'y' => 7), 'direction' => 'right', 'score' => 0, 'state' => true ); ``` 要將這些資料儲存在 URL 中,我們可以使用以下命令: ``` $url = urlencode(json_encode($state)); ``` 透過 JSON 編碼我們的陣列,然後用 URL 友好的字符替換無效字符,這以 URL 友好(儘管不是人類友好!)的方式為我們提供了狀態: ``` %7B%22width%22%3A20%2C%22height%22%3A20%2C%22snake%22%3A%5B%7B%22x%22%3A19%2C%22y%22%3A5%7D%5D%2C%22food%22%3A%7B%22x%22%3A4%2C%22y%22%3A11%7D%2C%22direction%22%3A%22right%22%2C%22score%22%3A0%2C%22state%22%3Afalse%7D ``` 現在我們有一個機制可以將遊戲狀態傳遞到瀏覽器並備份到伺服器。 ### 最大 URL 長度 那些了解自己的東西的人會知道這裡有一個問題。 URL 長度有最大限制! 在 Chrome 中是 2083 個字元。 如果您玩遊戲的時間足夠長,您實際上會達到字元限制,因為為了儲存 x,y 位置對,我們每次使用超過 10 個字元。 但這是一個愚蠢的演示,所以我只想說:讓我知道如果你讓你的蛇足夠長,會發生什麼錯誤! 哦,在現實世界中,**您不應該對 URL 中的參數進行 JSON 編碼**,我們就這樣吧! 我們有狀態和遊戲標記,現在怎麼辦? ----------------- 這就對了! 嗯,差不多了。 我們需要將按鍵資訊傳達給伺服器。 ### 問題3:改變蛇的方向 這是最後一個問題(也是我們最終在 URL 中顯示遊戲狀態的原因),我們需要向伺服器傳達按鍵訊息以更改蛇的方向。 #### 問題 3a:按下按鈕 在我們將按鍵傳達給伺服器之前,我們需要某種方法來實際捕獲它們。 請記住,我們沒有 JS 來捕獲按鍵操作。 我們也不能使用`<button>`元素,因為它們需要 JS 才能運作。 所以我們剩下的就是不起眼的錨元素( `<a>` )。 但讓某人點擊錨點會讓遊戲變得很難玩。 幸運的是,HTML 中內建了一種名為[`accesskey`的](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/accesskey)東西。 它們允許我們將一個字元指派給一個錨點,然後可以透過捷徑(ALT + Windows 上 Chrome 中的字元)存取這些字元。 這為我們提供了允許鍵盤控制的機制,我們只需要 4 個具有不同方向的連結(錨點)作為 URL,然後為每個連結分配一個`accesskey` 。 **重要提示:**應謹慎使用`accesskey` ,如果您選擇輔助科技 (AT) 使用者使用的按鍵,則可能會產生幹擾。 #### 問題 3b:方向 現在我們有了一種按鍵方法,以及一種將按鍵操作傳達給伺服器的方法,我們需要一種方法來管理按鍵操作,以便它們更新蛇的方向。 幸運的是,我們透過 URL 傳遞的狀態物件中已經有了一個`direction`屬性。 因此,我們要做的就是建立 4 個不同的 URL,每個方向一個。然後我們將這些加入到連結中就完成了。 ``` $encodedState = urlencode(json_encode($state)); <a href="index.php?state=<?php echo $encodedState; ?>&direction=up" accesskey="i">up (ALT + I)</a><br/> <a href="index.php?state=<?php echo $encodedState; ?>&direction=left" accesskey="j">left (ALT + J)</a> <a href="index.php?state=<?php echo $encodedState; ?>&direction=right" accesskey="l">right (ALT + L)</a> <a href="index.php?state=<?php echo $encodedState; ?>&direction=down" accesskey="k">down (ALT + K)</a> ``` 現在,例如,當您按ALT + K時,將單擊第四個連結,我們將當前狀態+新方向發送到伺服器! 現在剩下的就是獲取該資訊併計算下一個遊戲狀態。 ### 遊戲邏輯 最後,謎題的最後一部分是一些遊戲邏輯。 例如,在生成食物位置時,我們需要檢查它是否不在蛇已經佔據的圖塊上,因此我們有以下函數: ``` function generateFoodPosition($width, $height, $snake) { do { $food = array( 'x' => rand(0, $width - 1), 'y' => rand(0, $height - 1)); } while ( in_array($food, $snake) ); return $food; } ``` 還有一個移動蛇的功能 ``` function moveSnake($state) { $newHead = array('x' => $state['snake'][0]['x'], 'y' => $state['snake'][0]['y']); // Update snake's head position based on direction switch ($state['direction']) { case 'up': $newHead['y']--; break; case 'down': $newHead['y']++; break; case 'left': $newHead['x']--; break; case 'right': $newHead['x']++; break; } // Check if snake has collided with the wall or itself if ($newHead['x'] < 0 || $newHead['x'] >= $state['width'] || $newHead['y'] < 0 || $newHead['y'] >= $state['height'] || in_array($newHead, array_slice($state['snake'], 1))) { $state['state'] = false; return $state; // Game over } // Check if snake has eaten the food if ($newHead['x'] == $state['food']['x'] && $newHead['y'] == $state['food']['y']) { $state['score'] += 10; // Generate new food position $state['food'] = generateFoodPosition($state['width'], $state['height'], $state['snake']); } else { // Remove tail segment array_pop($state['snake']); } // Move snake array_unshift($state['snake'], $newHead); return $state; } ``` 以及建構遊戲板的循環。 ``` for ($y = 0; $y < 20; $y++) { echo "\r\n"; for ($x = 0; $x < 20; $x++) { if ($x == $state['food']['x'] && $y == $state['food']['y']) { echo '🍎'; } elseif (in_array(array('x' => $x, 'y' => $y), $state['snake'])) { echo '🟩'; }else{ echo '⬜'; } } } ``` 但我不會詳細介紹這些內容,因為您可以輕鬆找到(並找到更簡潔的方法)、找到其他人編寫的(更好的)程式碼並適應您的需求。 這是一個包裝 ------ 現在你已經知道了,我們使用元刷新、存取鍵和在 URL 中編碼複雜資料的技巧建立了一個遊戲。 這些東西對你的日常生活有用嗎?不,可能不會。 他們是否會在一個奇怪的邊緣情況下拯救你的屁股,完成這個工作,有能力使用黑客來交付產品情況?可能吧。 什麼?您沒想到我會提供您有用的教學嗎?你現在應該更清楚了。 但是,話雖如此,如果您確實喜歡這篇文章,或者奇蹟般地學到了一些新東西,請在下面給我留言,這真的意義重大! 祝大家週末愉快! 💗 --- 原文出處:https://dev.to/grahamthedev/snakein-pure-html-no-js-no-css-no-images-2ccg

讲讲前端工程化

## 前言 在2010年前,前端只是一个项目的“附赠品”,对于整个项目来说他显得无关紧要,甚至没有前后端之分,但后来为了提升用户体验,工程师们不得不把界面和交互做的更加优美和便捷,于是前端慢慢地脱离出来变成了一个单独地岗位和方向。 随着前端项目复杂度的提升,传统的前端开发方式(html+css+js)已经无法满足复杂多变的开发需求,因为无论是从开发效率、心智负担、时间成本等各个方面来看都是非常不划算的,于是工程师们为了解决这个问题,经过不断地探索和事件慢慢地形成了前端工程化的开发理念和实践方法。 ## 什么是前端工程化? 开局讲了这么多,但到底什么是前端工程化呢?请先看下面这个示意图: ![前端工程化.png][1] 简单来说,前端工程化就是指通过工具、流程和方法来提高前端开发效率、降低维护成本、增强代码质量的一种开发方式。 ## 如何实践前端工程化? ### 1. 项目构建时 使用如Vite、vue-cli、Create React App等开源前端脚手架,或者使用自己公司内部脚手架统一构建项目基础框架; ### 2. 项目开发时 - 协作开发&版本控制:我们可以使用git、svn等控制代码版本的迭代,也可以合理利用分支实现多人协作开发。 - 代码风格:在项目中配置Lint工具(如ESLint、Stylelint等),并定义一套符合团队规范的Lint规则,以保证代码风格的一致性。代码风格精确到命名规则、语言版本规范等。 - 模块化:将一些项目中通用的函数、类等代码单独封装到一个公共模块,并且区分出每个模块的职责,有利于代码维护,避免大多数冗余代码。 - 组件化:将一些高度可复用的组件尽量解耦封装成公共组件,实现一套组件多次使用,更有甚者可以单独抽离到组件库,可在多个项目重复利用。 ### 3. 测试阶段 - 单元测试:合理使用单元测试可以避免大多数bug的产生,尤其是在一些特殊场景下,比如涉及到支付等场景,单元测试尤为重要。 ### 4. 打包构建 使用打包工具,使用构建工具(如Webpack、Rollup等)对项目进行自动化构建,包括代码打包、压缩、转译、资源管理等,这样不仅可以有效减小代码体积,还可以利用babel对代码进行转译到兼容性最高的语言版本,减少设备兼容性问题。 ### 5. 自动化部署 - 持续集成/持续部署工具(CI/CD):CI/CD工具(如Jenkins、GitLab CI/CD等)可以在代码提交后自动触发构建、测试和部署流程,实现代码的自动化集成和部署。 - 容器化部署:使用容器化技术(如Docker、Kubernetes)可以将应用程序与其依赖项打包成一个容器,实现环境的统一和隔离,便于部署和管理。 - 自动化部署脚本:编写自动化部署脚本(如Shell脚本、Python脚本等),实现自动化地将代码从源代码库中拉取并部署到目标环境中。 以上就是简单的前端工程化内容了,希望能帮到你! [1]: https://www.zowlsat.com/usr/uploads/2024/02/3774073632.png

html/css 小分享:設定複選框和開關的樣式

我可能不是唯一一個對瀏覽器的預設`<input type="checkbox">`感到沮喪的開發人員。 首先:**它不可擴展。**在此範例中,字體大小已縮放至`200%` ,但複選框仍保持其根大小,即`13.333333px` : ![預設複選框](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/delpw47gyetj091jeun0.png) 在本教程中,我們將剖析瀏覽器的預設複選框,看看是否可以做得更好。 --- 首先,我們需要使用`appearance:none`清除預設樣式並設定初始大小 - 這將是一個相對單位`em` : ``` [type=checkbox] { appearance: none; aspect-ratio: 1; box-sizing: border-box; font-size: 1em; width: 1em; } ``` `background-color`應該適應深色模式,因此我們將檢查它是否與任何[系統顏色](https://developer.mozilla.org/en-US/docs/Web/CSS/system-color)相符。它似乎與`Field`系統顏色匹配,所以讓我們使用它。 對於 Chrome 中的邊框顏色,它與系統顏色`ButtonBorder`匹配,但由於 Safari 使用*更輕的*`ButtonBorder` ,我們將使用適用於兩種瀏覽器的`GrayCanvas` 。 我們將加入一些 CSS 自訂屬性,稍後我們將使用它們來建立變體。 對於`border-radius`和`margin` ,我們將使用預設值,但將它們轉換為相對單位`em` 。 `border-width`似乎使用以下公式進行縮放: ``` (4/3) / root size ``` 由於根大小為`13.333333px` ,我們現在有: ``` [type=checkbox] { --_bdw: calc(1em * (4/3) / 13.333333); appearance: none; aspect-ratio: 1; background: var(--_bg, Field); border: var(--_bdw) solid var(--_bdc, GrayText); border-radius: var(--_bdrs, .2em); box-sizing: border-box; font-size: 1em; margin: var(--_m, .1875em .1875em .1875em .25em); position: relative; width: 1em; } ``` 讓我們看看它是否可擴展: ![可擴充複選框](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dp6npvshq378jt0yk8o6.png) 好的!深色模式呢? ![深色模式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lm0aq2eixhf9or4ho67a.png) 這就是為什麼我**喜歡**系統顏色!接下來,讓我們新增瀏覽器在**未選取的**複選框上使用的相同懸停效果。 我們將混合`CanvasText` ,它在淺色模式下為黑色,在深色模式下為白色,並簡單地更新我們在上一步中加入的`--_bdc`屬性: ``` @media (hover: hover) { &:not(:checked):hover { --_bdc: color-mix(in srgb, GrayText 60%, CanvasText 40%); } } ``` --- 複選標記 ---- 現在是複選標記。我們**可以**在`::after`元素中使用旋轉的 CSS 方塊來做到這一點: ``` [type=checkbox]::after { border-color: GrayText; border-style: solid; border-width: 0 0.15em 0.15em 0; box-sizing: border-box; content: ''; aspect-ratio: 1 / 1.8; rotate: 40deg; width: 0.375em; } ``` ![CSS 中的複選標記](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/56ff7lvbtsljaxtoyt3h.png) 雖然這工作得很好,但我更喜歡在蒙版中使用 SVG,因為它更靈活。為此,我們將為遮罩加入一個屬性,並為`::after`元素的背景加入另一個`--_bga` ,該屬性將是複選標記的**顏色**。 ``` [role=checkbox] { --_bga: Field; --_mask: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" stroke-width="3" stroke="%23000" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path d="M5 12l5 5l10 -10"/></svg>'); &::after { background: var(--_bga, transparent); content: ""; inset: 0; position: absolute; mask: var(--_mask) no-repeat center / contain; -webkit-mask: var(--_mask) no-repeat center / contain; } } ``` 所以,我們現在**確實**有一個複選標記,只是看不到它,因為蒙版顏色設定為`transparent` 。 讓我們使用`:checked` -state 更新點擊時複選框的顏色。但在此之前,我們需要先弄清楚**哪種**顏色! Safari 是唯一支援系統顏色`AccentColor`瀏覽器,因此我們需要為此建立自己的變數`--_accent` ,在 Mac 上對應於`#0075ff` : ``` [type=checkbox] { --_accent: #0075ff; &:checked { --_bdc: transparent; --_bg: var(--_accent); --_bga: Field; } } ``` 讓我們看看我們建構了什麼: ![複選框樣式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9l3tzwwqkmrr4bpzrg19.png) 還有深色模式?我們需要先更新`--_accent`屬性,因為`AccentColor`尚未在所有瀏覽器中運作: ``` @media (prefers-color-scheme: dark) { --_accent: #99C8FF; } ``` 讓我們檢查: ![複選框深色模式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0kuid7fnr3obftfjr85s.png) 涼爽的!現在我們需要加入的是`:checked:hover` -state,它類似於我們之前新增的 border-hover: ``` @media (hover: hover) { &:checked:hover { --_bg: color-mix(in srgb, var(--_accent) 60%, CanvasText 40%); } } ``` 讓我們比較一下它在 Chrome、Safari 和 Firefox 中的外觀: ![瀏覽器比較](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hi9qej87nns2wjd4jqiw.png) 看來我們通過考驗了! --- 變體 -- 建立變體非常簡單:您只需要更新一些屬性。例子: ``` .rounded { --_bdrs: 50%; } .square { --_bdrs: 0; } ``` 然後在 HTML 中: ``` <input type="checkbox" class="rounded"> <input type="checkbox" class="square"> ``` ![變體](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vu5g82hu5zv65izekwsn.png) — 或全力以赴並建立*老式*複選框: ![老派複選框](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ngan912ja853wx4q8gil.png) > **關於圓形複選框的註釋:**這是*不好的*做法,正如您可以在[這篇精彩的文章](https://tonsky.me/blog/checkbox/)中讀到的那樣。不過,也有一些例外,例如這個「影像選擇器」: ![圓形影像選擇](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j36lzrpf7sxvimocpoud.png) 開關 -- 對於開關,我們將加入一個`role="switch"` ,所以它是: ``` <input type="checkbox" role="switch"> ``` 蘋果最近加入了[自己的 switch-control](https://dev.to/madsstoumann/a-first-look-at-apples-new-switch-control-3pnd) ,但`role="switch"`是跨瀏覽器的。同樣,我們只需要更新我們之前建立的許多屬性: ``` [role=switch] { --_bdc--hover: transparent; --_bdrs: 1em; --_bg: #d1d1d1; --_bga: Field; --_mask: none; aspect-ratio: 1.8 / 1; border: 0; display: grid; padding: .125em; place-content: center start; width: 1.8em; &::after { border-radius: 50%; height: .75em; inset: unset; position: static; width: .75em; } &:checked { --_bg: var(--_bg--checked, var(--_accent)); justify-content: end; } } ``` 這給了我們: ![開關](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2rlfyayxyzkqcr78qovn.png) --- 示範 -- 就是這樣!下面是帶有演示的 Codepen: https://codepen.io/stoumann/pen/OJqQNgm --- 駭客與縫合 ----- 以下是我在 Codepen 上使用複選框所做的一系列工作: ### 複選框電影院 選擇座位。還可以修改為在火車、飛機上選擇座位...... https://codepen.io/stoumann/pen/eYXpEBa ### 天際線複選框 點擊窗戶打開公寓裡的燈… https://codepen.io/stoumann/pen/KKbGJqd ### 按數字繪畫 先選擇一種顏色(使用`<input type="radio">` ),然後按一下對應的數字(複選框)... https://codepen.io/stoumann/pen/VwRejpR ### 點對點 不需要 JavaScript,但我把它留在那裡供你玩… https://codepen.io/stoumann/pen/zYbNRNL ### 來自地獄的條款和條件 檢查全部… https://codepen.io/stoumann/pen/GRwRjYP --- 每日 toggle ---- Alvaro Montoro 正在建立大量開關/撥動開關 - 2024 年每天一個。請[在此處](https://codepen.io/collection/aMPYMo)查看。 --- 原文出處:https://dev.to/madsstoumann/styling-checkboxes-and-switches-pf0

30 個 JavaScript 奇妙小技巧

歡迎使用我們精選的 JavaScript 技巧集合,它將幫助您優化程式碼、使其更具可讀性並節省您的時間。 讓我們深入研究 JavaScript 的功能和超越傳統的技巧,並發現這種強大的程式語言的全部潛力。 ### 1. 使用!!轉換為布林值 使用雙重否定快速將任何值轉換為布林值。 ``` let truthyValue = !!1; // true let falsyValue = !!0; // false ``` ### 2. 預設功能參數 設定函數參數的預設值以避免未定義的錯誤。 ``` function greet(name = "Guest") { return `Hello, ${name}!`; } ``` ### 3. 短 if-else 的三元運算符 `if-else`語句的簡寫。 ``` let price = 100; let message = price > 50 ? "Expensive" : "Cheap"; ``` ### 4. 動態字串的範本文字 使用模板文字在字串中嵌入表達式。 ``` let item = "coffee"; let price = 15; console.log(`One ${item} costs $${price}.`); ``` ### 5. 解構賦值 輕鬆從物件或陣列中提取屬性。 ``` let [x, y] = [1, 2]; let {name, age} = {name: "Alice", age: 30}; ``` ### 6. 用於陣列和物件克隆的擴展運算符 克隆陣列或物件而不引用原始陣列或物件。 ``` let originalArray = [1, 2, 3]; let clonedArray = [...originalArray]; ``` ### 7. 短路評估 使用邏輯運算子進行條件執行。 ``` let isValid = true; isValid && console.log("Valid!"); ``` ### 8. 可選連結 (?.) 如果引用為`nullish`則可以安全地存取巢狀物件屬性,而不會出現錯誤。 ``` let user = {name: "John", address: {city: "New York"}}; console.log(user?.address?.city); // "New York" ``` ### 9. 空合併運算子 (??) 使用`??`為`null`或`undefined`提供預設值。 ``` let username = null; console.log(username ?? "Guest"); // "Guest" ``` [![monday.com 的互動式橫幅展示了在數位介面上組織工作流程任務的雙手,並帶有「告訴我如何做」號召性用語按鈕。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xd7qdmxdd726kskelydk.png)](https://try.monday.com/9xf9ftaa4i2f) ### 10. 使用`map` 、 `filter`和`reduce`進行陣列操作 無需傳統循環即可處理陣列的優雅方法。 ``` // Map let numbers = [1, 2, 3, 4]; let doubled = numbers.map(x => x * 2); // Filter const evens = numbers.filter(x => x % 2 === 0); // Reduce const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); ``` ### 11.標記模板文字 使用模板文字進行函數呼叫以進行自訂字串處理。 ``` function highlight(strings, ...values) { return strings.reduce((prev, current, i) => `${prev}${current}${values[i] || ''}`, ''); } let price = 10; console.log(highlight`The price is ${price} dollars.`); ``` ### 12.使用Object.entries()和Object.fromEntries() 將物件轉換為陣列並返回以方便操作。 ``` let person = {name: "Alice", age: 25}; let entries = Object.entries(person); let newPerson = Object.fromEntries(entries); ``` ### 13. 唯一元素的集合物件 使用 Set 儲存任何類型的唯一值。 ``` let numbers = [1, 1, 2, 3, 4, 4]; let uniqueNumbers = [...new Set(numbers)]; ``` ### 14. 物件中的動態屬性名稱 在物件文字表示法中使用方括號來建立動態屬性名稱。 ``` let dynamicKey = 'name'; let person = {[dynamicKey]: "Alice"}; ``` ### 15. 使用bind()進行函數柯里化 建立一個新函數,在呼叫時將其 this 關鍵字設定為提供的值。 ``` function multiply(a, b) { return a * b; } let double = multiply.bind(null, 2); console.log(double(5)); // 10 ``` ### 16. 使用 Array.from() 從類別陣列物件建立陣列 將類似陣列或可迭代的物件轉換為真正的陣列。 ``` let nodeList = document.querySelectorAll('div'); let nodeArray = Array.from(nodeList); ``` ### 17. 可迭代物件的 for...of 循環 直接迭代可迭代物件(包括陣列、映射、集合等)。 ``` for (let value of ['a', 'b', 'c']) { console.log(value); } ``` ### 18. 使用 Promise.all() 實作並發 Promise 同時執行多個 Promise 並等待所有的都解決。 ``` let promises = [fetch(url1), fetch(url2)]; Promise.all(promises) .then(responses => console.log('All done')); ``` ### 19. 函數參數的剩餘參數 將任意數量的參數捕獲到陣列中。 ``` function sum(...nums) { return nums.reduce((acc, current) => acc + current, 0); } ``` [![Coursera Plus 訂閱產品包括 AWS 基礎、Google IT 支援專業憑證和商業網路安全專業化。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ys5gk2tfzcn4iniuq48s.png)](https://imp.i384100.net/c/3922519/1320997/14726) ### 20. 用於性能優化的記憶 儲存函數結果以避免冗餘處理。 ``` const memoize = (fn) => { const cache = {}; return (...args) => { let n = args[0]; // assuming single argument for simplicity if (n in cache) { console.log('Fetching from cache'); return cache[n]; } else { console.log('Calculating result'); let result = fn(n); cache[n] = result; return result; } }; }; ``` ### 21. 使用 ^ 交換值 使用 XOR 以位元運算子交換兩個變數的值,無需使用臨時變數。 ``` let a = 1, b = 2; a ^= b; b ^= a; a ^= b; // a = 2, b = 1 ``` ### 22. 使用 flat() 展平陣列 使用`flat()`方法輕鬆展平巢狀陣列,並將展平深度作為可選參數。 ``` let nestedArray = [1, [2, [3, [4]]]]; let flatArray = nestedArray.flat(Infinity); ``` ### 23. 用一元加法轉換為數字 使用一元加運算子快速將字串或其他值轉換為數字。 ``` let str = "123"; let num = +str; // 123 as a number ``` ### 24. HTML 片段的模板字串 使用模板字串建立 HTML 片段,使動態 HTML 生成更加清晰。 ``` let items = ['apple', 'orange', 'banana']; let html = `<ul>${items.map(item => `<li>${item}</li>`).join('')}</ul>`; ``` ### 25. 使用 Object.assign() 合併物件 將多個來源物件合併到一個目標物件中,有效地組合它們的屬性。 ``` let obj1 = { a: 1 }, obj2 = { b: 2 }; let merged = Object.assign({}, obj1, obj2); ``` [![符合人體工學的垂直滑鼠旨在減輕手腕壓力](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/56c0z4lzxtkthnnk8gsb.jpg)](https://amzn.to/3UXGIyx) 使用符合人體工學的滑鼠優化您的編程設置,專為舒適和長時間的編碼會話而定制。 ### 26. 預設值短路 處理潛在的未定義或空變數時,使用邏輯運算子指派預設值。 ``` let options = userOptions || defaultOptions; ``` ### 27. 使用括號表示法動態存取物件屬性 使用括號表示法動態存取物件的屬性,當屬性名稱儲存在變數中時非常有用。 ``` let property = "name"; let value = person[property]; // Equivalent to person.name ``` ### 28. 使用 Array.includes() 進行存在檢查 使用includes() 檢查陣列是否包含某個值,它是indexOf 的更清晰的替代方法。 ``` if (myArray.includes("value")) { // Do something } ``` ### 29. Function.prototype.bind() 的強大功能 將函數綁定到上下文(此值)並部分套用參數,以建立更多可重複使用和模組化的程式碼。 ``` const greet = function(greeting, punctuation) { return `${greeting}, ${this.name}${punctuation}`; }; const greetJohn = greet.bind({name: 'John'}, 'Hello'); console.log(greetJohn('!')); // "Hello, John!" ``` ### 30.防止物件修改 使用`Object.freeze()`防止物件進行修改,使其不可變。對於更深層的不變性,請考慮更徹底地強制不變性的函式庫。 ``` let obj = { name: "Immutable" }; Object.freeze(obj); obj.name = "Mutable"; // Fails silently in non-strict mode ``` 我希望這些 JavaScript 技巧為您提供如何進行[JavaScript 程式設計的](https://www.w3schools.com/js/)新視角。 從利用模板文字的簡潔功能到掌握`map` 、 `filter`和`reduce`的效率,這些 JavaScript 技巧將豐富您的開發工作流程並激發您的下一個專案。 讓這些 JavaScript 技巧不僅可以完善您目前的專案,還可以在您的[程式設計之旅](https://www.webdevstory.com/programming-roadmap/)中激發未來創新的靈感。 ***支持我們的技術見解*** [![請我喝杯咖啡](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lsm9uucbnw7x9iw0loxr.png)](https://www.buymeacoffee.com/mmainulhasan) [![透過 PayPal 按鈕捐贈](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ipnhbim2ba56kt32zhn3.png)](https://www.paypal.com/donate/?hosted_button_id=GDUQRAJZM3UR8) 注意:此頁面上的某些連結可能是附屬連結。如果您透過這些連結進行購買,我可能會賺取少量佣金,而無需您支付額外費用。感謝您的支持! --- 原文出處:https://dev.to/mmainulhasan/30-javascript-tricky-hacks-gfc

JavaScript 中的 async 與 defer:哪個更好?🤔

大家好!我希望你一切都好。本文將探討一個有趣的 Javascript 主題。 `async`和`defer`是在 HTML 文件中包含外部 JavaScript 檔案時使用的屬性。它們會影響瀏覽器載入和執行腳本的方式。讓我們詳細了解一下它們。 預設行為 ---- 我們通常使用`<script>`標籤將 HTML 頁面與外部 javascript 連接。傳統上,JavaScript `<script>`標籤通常放置在 HTML 文件的`<head>`部分。然而,這樣做意味著 HTML 的解析會被阻止,直到 JavaScript 檔案被取得並執行為止,導致頁面載入時間變慢。如今,我們更喜歡在頁面的`<body>`元素的所有內容首先加載之後保留`<script>`標記。 ``` <script src="example.js"></script> ``` HTML 解析和腳本執行的過程如下 ![預設](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8cvwth1dxa1gjtv7fa9d.png) 非同步 --- 當我們包含具有 async 屬性的腳本時,它會告訴瀏覽器在解析 HTML 文件時非同步下載腳本。腳本在背景下載,不會阻塞 HTML 解析過程。 下載腳本後,它會非同步執行,這意味著它可以隨時執行,甚至在 HTML 文件完成解析之前也可以執行。 ``` <script src="example.js" async></script> ``` 如果非同步載入多個腳本,它們將在下載完成後立即執行,無論它們在文件中的順序如何。當腳本不依賴完全載入的 DOM 或其他腳本時,它非常有用。 ![非同步](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rdc0ui3yp1rnbag7psgr.png) 延遲 -- 當我們包含具有 defer 屬性的腳本時,它也會告訴瀏覽器在解析 HTML 文件時非同步下載腳本。 然而,腳本的執行被推遲到 HTML 文件被解析之後。 ``` <script src="example.js" defer></script> ``` 具有 defer 屬性的腳本將按照它們在文件中出現的順序執行。當腳本依賴完全解析的 DOM 或腳本執行順序很重要時,它非常有用。 ![延遲](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uh5mo1x1pl3y3zpkgpeg.png) 結論 -- async 和 defer 都允許 HTML 解析過程繼續進行,而無需等待腳本下載。 差別在於腳本執行的時間: 使用非同步,腳本在下載後立即執行,可能在 HTML 文件完全解析之前執行。使用 defer,腳本僅在 HTML 文件完全解析之後、 `DOMContentLoaded`事件之前執行。 需要注意的重要事項之一是,只有當我們有可以獨立執行且不依賴 DOM 結構的腳本時,我們才應該使用 async,而當我們需要維護腳本執行順序或依賴 DOM 時,我們應該使用 defer結構。 我希望您喜歡這篇文章,如果您喜歡,請不要忘記按讚! 😃 **與我聯絡-** - [推特](https://twitter.com/fidalmathew10) - [github](https://github.com/FidalMathew) - [領英](https://www.linkedin.com/in/fidalmathew/) --- 原文出處:https://dev.to/fidalmathew/async-vs-defer-in-javascript-which-is-better-26gm

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

4 分鐘解釋 JWT

https://youtu.be/0WH9oiYMS3M 介紹 == JWT 身份驗證和會話身份驗證是對 Web 應用程式使用者進行身份驗證的方法。 在本文中,我們將解釋 JWT 的詳細資訊、其結構及其優缺點。 JWT 代表**JSON Web Token** ,它是一種常用的無狀態用戶身份驗證[標準](https://datatracker.ietf.org/doc/html/rfc7519),用於以 JSON 格式在用戶端和伺服器之間安全地傳輸資訊。 預設情況下,JWT 已編碼但未加密。 它使用只有伺服器知道的密鑰進行數位簽署。 它可以加密,但在本文中,我們將重點放在簽署的非加密令牌。 JWT 的結構 ======= JSON Web 令牌由以句點分隔的 3 個部分組成。 標頭、有效負載和簽名。 每個部分均採用 Base64 編碼。 ![JWT編碼結構](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ur5abitdnsxnmlpzs2pk.png) ### 標頭 標頭由令牌類型(JWT)和使用的簽章演算法(例如 HMAC SHA256 或 RSA)組成。 ``` { "typ": "JWT", "alg": "HS256" } ``` ### 有效載荷 有效負載由聲明組成。 聲明是關於用戶的聲明和附加資料。 例如,我們有令牌的發行時間。 我們也有它的過期時間,因為令牌應該過期。 ``` { "iss": "example_issuer", "sub": "user_id123", "exp": 1644768000, "iat": 1644744000 } ``` ### 簽名 簽名是 JWT 最重要的部分。 它是使用標頭、有效負載和秘密進行計算的,這些資訊將饋送到簽名演算法中使用。 ``` signature = HMAC-SHA256(base64urlEncode(header) + "." + base64urlEncode(payload), secret_salt ) ``` ![JWT 結構解碼](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o72ktulq29hondu66rbe.png) 步驟 == 典型的 JWT 授權流程涉及的步驟如下: **1- 身份驗證:**使用者使用使用者名稱和密碼登錄,或使用 Google 或 Facebook 等。 伺服器驗證提供的憑證。 **2- 令牌產生並將令牌發送到客戶端:**伺服器將產生 JWT 並將其發送到客戶端,客戶端儲存它以供將來使用。 **3-將令牌傳送到伺服器:**當客戶端想要存取伺服器上受保護的資源時,它會在 HTTP 請求的 Authorization 標頭中傳送 JWT。 ``` axios.get(URL, { headers: { 'Authorization': 'Bearer ' + token, }, }) ``` **4-驗證令牌:**伺服器接收請求並透過使用用於簽署的金鑰檢查其簽章來驗證 JWT。 如果 JWT 有效,伺服器會提取其中包含的資訊並使用它來確定使用者有權執行哪些操作。 **5-授權請求:**如果使用者被授權存取資源,伺服器將傳回請求的資料。如果用戶未獲得授權,伺服器將傳回錯誤訊息。 ![智威湯遜流程](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/igvye1880i9491jbz525.png) **優點** ====== ![智威湯遜優勢](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mg76chqzkpoz8pb7o9dt.png) - 輕的 - 便攜式:可在多個平台、網路和行動平台上處理。 - JSON 解析器在大多數程式語言中都很常見。 - 由於密鑰儲存在伺服器端,因此可以防止篡改。 - 由於 JWT 令牌的無狀態性質,伺服器不需要儲存任何會話資訊。 缺點 == ![缺點](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jmvzoi46hyd3wt8t6hpp.png) - 在伺服器端,應在登出時手動將未過期的 JWT 標記為無效。 即使 JWT 從客戶端刪除後仍然有效。 ![JWT 仍然有效](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fdrm27cehhd0bck5djzt.png) 使用的方法是令牌黑名單,它涉及在伺服器端維護無效令牌的列表,以防止它們重新用於身份驗證。 ![令牌黑名單](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wultrfhdmneg7yoqtyv8.png) - 對於簽署的非加密令牌,我們不應該儲存敏感訊息,因為 JWT 可以防止篡改,但任何人都可以解碼和讀取。 - 如果被攔截,可以提供完全存取權。這就是為什麼客戶端的 JWT 應該儲存在安全的地方,例如在瀏覽器中的 HttpOnly cookie 中。 --- 原文出處:https://dev.to/jaypmedia/jwt-explained-in-4-minutes-with-visuals-g3n

Taipy 3.1:視覺化與資料管理的新時代

社區開發者您好! 我非常高興與您分享我們旅程中的最新飛躍 - Taipy 3.1 的發布。我們的團隊一直在努力整合回饋並突破我們平台的界限。讓我們深入探討 3.1 為何能改變遊戲規則。 ![我太激動了](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c71osnbbtt7nqlxs9rzd.gif) --- #### 第三方元件集成 您是否曾經希望能夠將您喜愛的 Python 庫無縫整合到您的 Taipy 應用程式中?不再希望了! 在 3.1 中,我們可以視覺化 Taipy 的多功能**零件物件**中的任何**HTML**或**Python 物件**。 這意味著[Folium](https://python-visualization.github.io/folium/latest/) 、 [Bokeh](https://bokeh.org/) 、 [Vega-Altair](https://altair-viz.github.io/)和[Matplotlib](https://matplotlib.org/)等庫現在觸手可及,隨時可以透過動態且引人入勝的視覺化來豐富您的應用程式。最好的部分是什麼?這一切都被簡化為單一、有凝聚力的使用者體驗。 [閱讀發行說明](https://links.taipy.io/RelNotes) ![Taipy第三方元件集成](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1gooc3i0r0czo07ka71s.gif) --- ### 原生情節集成 陰謀愛好者,歡欣鼓舞! Taipy 3.1 帶來了對[Plotly Python 的](https://plotly.com/python/)原生支持,改變了您將複雜圖表整合到應用程式中的方式。解決方法整合的日子已經一去不復返了。現在,一行程式碼即可嵌入任何 Plotly 圖表,保持 Taipy 聞名的高效能和互動性。這是最好的資料視覺化——直觀、高效且視覺上令人驚嘆。 [閱讀發行說明](https://links.taipy.io/RelNotes) ![原生情節集成](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/05slwiwgdcv5sdmsub9p.gif) --- ### 分散式運算 隨著資料集的成長和運算需求的增加,企業需要可擴展的解決方案。認識到這一點,我們在 Taipy 3.1 中引入了分散式計算。此功能允許在多台機器上分配計算任務,從而增強大規模資料專案的效能。它的目的是更快、更有高效,使企業能夠輕鬆處理複雜的運算。 [閱讀發行說明](https://links.taipy.io/RelNotes) ![分散式運算](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eqemztz5kz8gxvtadx4u.gif) --- ### 遙測 保持應用程式的健康和性能至關重要。透過 Taipy 3.1 的遙測功能,管理員和開發人員可以獲得對應用程式效能指標和執行狀況指標的重要見解。這種主動監控工具旨在保持營運平穩並在潛在問題升級之前辨識它們,確保您的應用程式以最佳狀態執行。 [閱讀發行說明](https://links.taipy.io/RelNotes) ![遙測](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q6wdqip7umwq00d1w3lx.png) --- > ### Python 3.12 支持 > 我們也很高興地宣布 Taipy 及其所有依賴項現在與 Python 3.12 完全相容。此更新可確保您使用 Python 提供的最新、最強大的功能,進一步增強資料專案的穩健性和可靠性。 --- 無論您是第一次深入資料專案還是領導複雜的企業解決方案,此版本都旨在提升您的工作。 我們很高興看到我們的社群將利用這些新功能建立創新的應用程式和解決方案。如果您和我們一樣渴望探索可能性,請加入[Discord](https://discord.com/invite/SJyz2VJGxV)上充滿活力的開發人員和資料科學家社群。我們可以共同塑造 Python 應用程式開發的未來。 感謝您一直以來的支持與熱情。讓 Taipy 成為滿足您的資料科學需求的首選框架。 您可以在[GitHub](github.com/Avaiga/taipy)上為我們的儲存庫加註星標 --- 原文出處:https://dev.to/taipy/taipy-31-a-new-era-of-visualization-and-data-management-1abg

為什麼事件溯源是微服務通訊的反模式

--- 標題:為什麼事件溯源是一種微服務通訊反模式 發表:真實 描述:這篇文章描述了合理的事件溯源用例,並提供了微服務之間通訊的替代方案。 封面圖片:https://github.com/OLibutzki/blog/raw/master/water-4230596\_1920.jpg 標籤: 事件溯源, 領域驅動設計, 領域事件 --- 一般而言,事件驅動架構,特別是事件溯源,在過去幾年中獲得了廣泛關注。這種趨勢是由於我們努力建構具有彈性和可擴展性的模組化系統而引起的。*微服務*是在這種情況下經常使用的術語。在我看來,微服務只是實現有界脈絡的一種方法。模組化系統的核心是模組的邊界,而如何辨識這些邊界最有前途的想法是 Eric Evans 的領域驅動設計中引入的[戰略設計](https://en.wikipedia.org/wiki/Domain-driven_design#Strategic_domain-driven_design)。它可以幫助您辨識/發現模組及其邊界([有界上下文](https://martinfowler.com/bliki/BoundedContext.html)),並描述這些有界上下文相互關聯的方式(上下文映射)。 *注意:我會預設某些術語的一些預知,因為我不想第一千次解釋它們。我決定連結到[microservices.io](https://microservices.io/) 、[維基百科](https://en.wikipedia.org)或[Martin Fowler 的 Bliki](https://martinfowler.com/bliki/)的解釋,因此,如果您對自己的知識感到不舒服,則可以更深入地研究某個主題。* 領域事件作為通用語言的核心 ============= 儘管在 Eric 的書中沒有明確提及,但領域事件很好地促進了 DDD 概念的發展。像 Alberto Brandolini 的[事件風暴](https://en.wikipedia.org/wiki/Event_storming)這樣的技術將事件的焦點從技術層面轉移到組織/業務層面。我們不討論一些 UI 層事件,例如*ButtonClickedEvent* ,而是討論領域事件,它們是業務領域的一部分,並由業務專家說出和理解。這些領域事件是一流的概念,並提供了一種形成所有參與者(領域專家、開發人員…)都同意的[通用語言的](https://martinfowler.com/bliki/UbiquitousLanguage.html)好方法。 用於跨界通訊的領域事件 =========== 領域事件可用於促進有界上下文之間的溝通。假設我們有一家具有三個限界上下文的線上商店:訂單、交貨、發票。 訂單上下文的網域事件是*訂單已接受*。發票和交付上下文對此事件的發生感興趣,因為它會導致一些內部流程啟動。 脫鉤神話 ==== 使用領域事件可以幫助您開發解耦的模組。模組可能會暫時離線。領域事件不關心不可用的模組,它們描述過去發生的事情。這取決於其他模組處理事件的速度。您得到的是一個設計上具有彈性的系統。 除了時間解耦之外,領域事件還具有另一個優勢,至少乍看之下是這樣: Order 上下文不必知道 Invoice 和 Delivery 上下文會偵聽其事件。實際上它甚至不需要知道這些上下文的存在。 這很酷,但具有挑戰性的部分是事件負載。哪些資料放入事件中? 簡單的答案:事件溯源! =========== 事件很有用,所以為什麼不賦予它們盡可能多的權力(和責任)。這就是[事件溯源](https://microservices.io/patterns/data/event-sourcing.html)的基本思想。您不會透過更新資料 (CRUD) 而是透過套用事件流來儲存聚合的狀態。 除了您可以重播事件以重建應用程式狀態之外,事件來源的一個重要功能是您可以免費獲得完整且可靠的審核日誌。因此,當需要這樣的稽核日誌時,在評估持久性策略時一定要考慮事件溯源。 事件溯源只是一種持久性策略嗎? =============== 您可能想知道為什麼我從領域事件直接轉向持久化策略,因為這些概念顯然適用於不同的層/抽象層級。 ……這就是我的觀點:事件溯源是由單一限界上下文做出的本地決策!這些事件不該向外界曝光!其他限界上下文則不知道彼此的持久化策略,因此它們不知道也不關心另一個限界上下文是否使用事件溯源。 如果您在全球範圍內使用事件溯源,則會暴露您的持久層。 您的持久性將成為您的公共 API。每次限界上下文調整其持久性資料時,我們都必須處理公共 API 變更。 我很確定每個人都同意,由於開發和執行時耦合,不同的限界上下文[共享(關係)資料庫中的資料](https://microservices.io/patterns/data/shared-database.html)是一個壞主意。但差別在哪裡呢? 空無一人。我們是否共享事件或資料庫表並不重要。在這兩種情況下,我們都會分享持久性詳細資訊。 有出路 === 我仍然認為領域事件非常適合限界上下文之間的通信,但這些事件不應與用於事件溯源的事件相對應。 我提出的解決方案是合乎邏輯的結果:無論您使用 CRUD 還是事件溯源方法來實現持久性,您都可以將領域事件發佈到全域事件儲存。這些領域事件是有界上下文的公共 API。如果您喜歡在限界上下文中使用事件溯源,則可以將這些事件儲存在本機事件儲存中,該儲存只能從此限界上下文存取 選擇的自由 ===== 在公共 API 中擁有專用領域事件可讓您決定如何對這些事件建模。您不受事件來源事件預先定義的佈局的限制。 對於每次發生的“現實世界事件”,您有兩個選擇: 使用已發布語言的開放主機服務 -------------- 準確發布一個網域事件,其中包含其他限界上下文可能需要的所有資料。在 DDD 術語中,我們將其稱為具有已發布語言的開放主機服務。 ![使用已發布語言的開放主機服務](https://raw.githubusercontent.com/OLibutzki/blog/master/OpenHostService.png) 現實世界事件*Order Accepted*的發生會導致發布一個網域事件*OrderAccepted* 。此事件的有效負載包含 Order 期望其他限界上下文感興趣的所有資料...因此希望 Invoice 和 Delivery 上下文找到它們所需的所有資訊。 客戶/供應商 ------ 發布多個專用領域事件,每個事件使用者一個。您必須與另一方(消費者)討論每個特定的領域事件,而不必定義共享模型。 DDD 將這種關係稱為客戶/供應商。 ![客戶/供應商](https://github.com/OLibutzki/blog/raw/master/CustomerSupplier.png) 現實世界事件*Order Accepted*的發生會導致每個消費限界上下文發布一個網域事件: *InvoiceOrderAccepted*和*DeliveryOrderAccepted* 。每個領域事件都包含消費上下文所請求的資料。 我不想討論這兩種選擇的優缺點。我只是想強調一下,您可以自由選擇領域事件的數量及其有效負載。 這是您不應低估的巨大優勢,因為您可以決定如何發展有界上下文的 API,而不必致力於事件溯源所需的事件。 結論 == 向外界公開持久性細節是一種眾所周知的反模式。在談論持久性時,我們首先想到的是資料庫表,但我解釋了為什麼用於事件來源的事件只是持久性資料的另一種方式。因此,暴露這些事件也是一種反模式。 {% 推特 784691906005635072 %} 如果以適當的(本地)方式使用事件溯源,它會非常強大。乍一看,它似乎是事件驅動架構的靈丹妙藥,但如果您深入研究,您會意識到它可能會引導您進入緊密耦合(分散式)系統……當然,這不是您的目標。 參考 == 除了我的個人經驗之外,我還從不同的摘要和會議演講中獲得了許多靈感。我想重點介紹 Eberhard Wolff 的演講《*基於事件的架構以及使用 Kafka 和 Atom 的實現》* 。特別是[事件溯源](https://youtu.be/Ecg7lvvm8aU?t=1178)和[事件中有什麼?](https://youtu.be/Ecg7lvvm8aU?t=655)與本博文的上下文高度相關。我選擇的線上商店範例是受到這次演講的啟發。 如果您想獲取更多訊息,還可以查閱其他一些資源: - [領域事件與事件溯源,](https://www.innoq.com/en/blog/domain-events-versus-event-sourcing/)作者:Christian Stettler,部落格文章 - [關於事件溯源,他們沒有告訴您的事情](https://medium.com/@hugo.oliveira.rocha/what-they-dont-tell-you-about-event-sourcing-6afc23c69e9a)由 Hugo Rocha 撰寫,部落格文章 - [DDD、CQRS、事件溯源的十年(CQRS/ES 不是頂級架構),](https://youtu.be/LDW0QWie21s?t=1259)作者:Greg Young,會議演講 --- 原文出處:https://dev.to/olibutzki/why-event-sourcing-is-a-microservice-anti-pattern-3mcj

我正在建立一個全端應用程式:以下是我將要使用的庫......

您可以使用無數的框架和函式庫來改進您的全端應用程式。 我們將介紹令人興奮的概念,例如應用程式內通知、使用 React 製作影片、從為開發人員提供的電子郵件 API 到在瀏覽器中建立互動式音樂。 那我們就開始吧。 (不要忘記為這些庫加註星標以表示您的支持)。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qqoipyuoxgb83swyoo4a.gif) https://github.com/CopilotKit/CopilotKit --- 1. [CopilotKit](https://github.com/CopilotKit/CopilotKit) - 在數小時內為您的產品提供 AI Copilot。 ------------------------------------------------------------------------------------ ![副駕駛套件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nzuxjfog2ldam3csrl62.png) 您可以使用兩個 React 元件將關鍵 AI 功能整合到 React 應用程式中。它們還提供內建(完全可自訂)Copilot 原生 UX 元件,例如`<CopilotKit />` 、 `<CopilotPopup />` 、 `<CopilotSidebar />` 、 `<CopilotTextarea />` 。 開始使用以下 npm 指令。 ``` npm i @copilotkit/react-core @copilotkit/react-ui @copilotkit/react-textarea ``` 這是整合 CopilotTextArea 的方法。 ``` import { CopilotTextarea } from "@copilotkit/react-textarea"; import { useState } from "react"; export function SomeReactComponent() { const [text, setText] = useState(""); return ( <> <CopilotTextarea className="px-4 py-4" value={text} onValueChange={(value: string) => setText(value)} placeholder="What are your plans for your vacation?" autosuggestionsConfig={{ textareaPurpose: "Travel notes from the user's previous vacations. Likely written in a colloquial style, but adjust as needed.", chatApiConfigs: { suggestionsApiConfig: { forwardedParams: { max_tokens: 20, stop: [".", "?", "!"], }, }, }, }} /> </> ); } ``` 您可以閱讀[文件](https://docs.copilotkit.ai/getting-started/quickstart-textarea)。 基本概念是在幾分鐘內建立可用於基於 LLM 的全端應用程式的 AI 聊天機器人。 https://github.com/CopilotKit/CopilotKit --- 2. [Storybook](https://github.com/storybookjs/storybook) - UI 開發、測試和文件變得簡單。 --------------------------------------------------------------------------- ![故事書](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/78rfum1ydisn51qhb408.png) Storybook 是一個用於獨立建立 UI 元件和頁面的前端工作坊。它有助於 UI 開發、測試和文件編制。 他們在 GitHub 上有超過 57,000 次提交、81,000 多個 star 和 1300 多個版本。 這是您為專案建立簡單元件的方法。 ``` import type { Meta, StoryObj } from '@storybook/react'; import { YourComponent } from './YourComponent'; //👇 This default export determines where your story goes in the story list const meta: Meta<typeof YourComponent> = { component: YourComponent, }; export default meta; type Story = StoryObj<typeof YourComponent>; export const FirstStory: Story = { args: { //👇 The args you need here will depend on your component }, }; ``` 您可以閱讀[文件](https://storybook.js.org/docs/get-started/setup)。 如今,UI 除錯起來很痛苦,因為它們與業務邏輯、互動狀態和應用程式上下文糾纏在一起。 Storybook 提供了一個獨立的 iframe 來渲染元件,而不會受到應用程式業務邏輯和上下文的干擾。這可以幫助您將開發重點放在元件的每個變體上,甚至是難以觸及的邊緣情況。 https://github.com/storybookjs/storybook --- 3. [Appwrite](https://github.com/appwrite/appwrite) - 您的後端減少麻煩。 --------------------------------------------------------------- ![應用程式寫入](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8x568uz21seyygw6b72z.png) ![帶有 appwrite 的 sdk 列表](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cp7k8qnamsluto7eifpl.png) Appwrite 的開源平台可讓您將身份驗證、資料庫、函數和儲存體新增至您的產品中,並建立任何規模的任何應用程式、擁有您的資料並使用您喜歡的編碼語言和工具。 他們有很好的貢獻指南,甚至不厭其煩地詳細解釋架構。 開始使用以下 npm 指令。 ``` npm install appwrite ``` 您可以像這樣建立一個登入元件。 ``` "use client"; import { useState } from "react"; import { account, ID } from "./appwrite"; const LoginPage = () => { const [loggedInUser, setLoggedInUser] = useState(null); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [name, setName] = useState(""); const login = async (email, password) => { const session = await account.createEmailSession(email, password); setLoggedInUser(await account.get()); }; const register = async () => { await account.create(ID.unique(), email, password, name); login(email, password); }; const logout = async () => { await account.deleteSession("current"); setLoggedInUser(null); }; if (loggedInUser) { return ( <div> <p>Logged in as {loggedInUser.name}</p> <button type="button" onClick={logout}> Logout </button> </div> ); } return ( <div> <p>Not logged in</p> <form> <input type="email" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} /> <input type="password" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} /> <input type="text" placeholder="Name" value={name} onChange={(e) => setName(e.target.value)} /> <button type="button" onClick={() => login(email, password)}> Login </button> <button type="button" onClick={register}> Register </button> </form> </div> ); }; export default LoginPage; ``` 您可以閱讀[文件](https://appwrite.io/docs)。 Appwrite 可以非常輕鬆地建立具有開箱即用的擴充功能的可擴展後端應用程式。 https://github.com/appwrite/appwrite --- 4. [Wasp](https://github.com/wasp-lang/wasp) - 用於 React、node.js 和 prisma 的類似 Rails 的框架。 --------------------------------------------------------------------------------------- ![黃蜂](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fi2mwazueoc3ezjx8a9q.png) 使用 React 和 Node.js 開發全端 Web 應用程式的最快方法。這不是一個想法,而是一種建立瘋狂快速全端應用程式的不同方法。 這是將其整合到元件中的方法。 ``` import getRecipes from "@wasp/queries/getRecipes"; import { useQuery } from "@wasp/queries"; import type { User } from "@wasp/entities"; export function HomePage({ user }: { user: User }) { // Due to full-stack type safety, `recipes` will be of type `Recipe[]` here. const { data: recipes, isLoading } = useQuery(getRecipes); // Calling our query here! if (isLoading) { return <div>Loading...</div>; } return ( <div> <h1>Recipes</h1> <ul> {recipes ? recipes.map((recipe) => ( <li key={recipe.id}> <div>{recipe.title}</div> <div>{recipe.description}</div> </li> )) : 'No recipes defined yet!'} </ul> </div> ); } ``` 您可以閱讀[文件](https://wasp-lang.dev/docs)。 https://github.com/wasp-lang/wasp --- 5. [Novu](https://github.com/novuhq/novu) - 將應用程式內通知新增至您的應用程式! -------------------------------------------------------------- ![再次](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/716b7biilet4auudjlcu.png) Novu 提供開源通知基礎架構和功能齊全的嵌入式通知中心。 這就是如何使用`React`建立 novu 元件以用於應用程式內通知。 ``` import { NovuProvider, PopoverNotificationCenter, NotificationBell, } from "@novu/notification-center"; function App() { return ( <> <NovuProvider subscriberId={process.env.REACT_APP_SUB_ID} applicationIdentifier={process.env.REACT_APP_APP_ID} > <PopoverNotificationCenter> {({ unseenCount }) => <NotificationBell unseenCount={unseenCount} />} </PopoverNotificationCenter> </NovuProvider> </> ); } export default App; ``` 您可以閱讀[文件](https://docs.novu.co/getting-started/introduction)。 https://github.com/novuhq/novu --- 6. [Remotion](https://github.com/remotion-dev/remotion) - 使用 React 以程式設計方式製作影片。 ------------------------------------------------------------------------------- ![遠端](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wmnrxhsc7b9mm5oagflm.png) 使用 React 建立真正的 MP4 影片,使用伺服器端渲染和參數化擴展影片製作。 開始使用以下 npm 指令。 ``` npm init video ``` 它為您提供了一個幀號和一個空白畫布,您可以在其中使用 React 渲染任何您想要的內容。 這是一個範例 React 元件,它將當前幀渲染為文字。 ``` import { AbsoluteFill, useCurrentFrame } from "remotion";   export const MyComposition = () => { const frame = useCurrentFrame();   return ( <AbsoluteFill style={{ justifyContent: "center", alignItems: "center", fontSize: 100, backgroundColor: "white", }} > The current frame is {frame}. </AbsoluteFill> ); }; ``` 您可以閱讀[文件](https://www.remotion.dev/docs/)。 過去兩年,remotion 團隊因製作 GitHub Wrapped 而聞名。 https://github.com/remotion-dev/remotion --- [7.NocoDB](https://github.com/nocodb/nocodb) - Airtable 的替代品。 ------------------------------------------------------------- ![諾科資料庫](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iw3tchfgyzehye5c39xq.png) Airtable 的免費開源替代品是 NocoDB。它可以使用任何 MySQL、PostgreSQL、SQL Server、SQLite 或 MariaDB 資料庫製作智慧型電子表格。 其主要目標是讓強大的計算工具得到更廣泛的使用。 開始使用以下 npx 指令。 ``` npx create-nocodb-app ``` 您可以閱讀[文件](https://docs.nocodb.com/)。 NocoDB 的建立是為了為世界各地的數位企業提供強大的開源和無程式碼資料庫介面。 您可以非常快速地將airtable資料匯入NocoDB。 https://github.com/nocodb/nocodb --- 8.[新穎](https://github.com/steven-tey/novel)- 所見即所得編輯器,具有人工智慧自動完成功能。 ------------------------------------------------------------------- ![小說](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uo34vd9twpxcpbpzgchi.png) 它使用`Next.js` 、 `Vercel AI SDK` 、 `Tiptap`作為文字編輯器。 開始使用以下 npm 指令。 ``` npm i novel ``` 您可以這樣使用它。有多種選項可用於改進您的應用程式。 ``` import { Editor } from "novel"; export default function App() { return <Editor />; } ``` https://github.com/steven-tey/novel --- 9. [Blitz](https://github.com/blitz-js/blitz) - 缺少 NextJS 的全端工具包。 ----------------------------------------------------------------- ![閃電戰](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vz6ineg1o7xyv7pwbuqn.png) Blitz 繼承了 Next.js 的不足,為全球應用程式的交付和擴展提供了經過實戰考驗的函式庫和約定。 開始使用以下 npm 指令。 ``` npm install -g blitz ``` 這就是您如何使用 Blitz 建立新頁面。 ``` const NewProjectPage: BlitzPage = () => { const router = useRouter() const [createProjectMutation] = useMutation(createProject) return ( <div> <h1>Create New Project</h1> <ProjectForm submitText="Create Project" schema={CreateProject} onSubmit={async (values) => { // This is equivalent to calling the server function directly const project = await createProjectMutation(values) // Notice the 'Routes' object Blitz provides for routing router.push(Routes.ProjectsPage({ projectId: project.id })) }} /> </div> ); }; NewProjectPage.authenticate = true NewProjectPage.getLayout = (page) => <Layout>{page}</Layout> export default NewProjectPage ``` 您可以閱讀[文件](https://blitzjs.com/docs/get-started)。 它使建築物改善了數倍。 ![閃電戰](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cc4mb5wdksjv1ybx71co.png) https://github.com/blitz-js/blitz --- 10. [Supabase](https://github.com/supabase/supabase) - 開源 Firebase 替代品。 ----------------------------------------------------------------------- ![蘇帕貝斯](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ksfygjhrzhmsg9cnvobs.png) 我們大多數人都已經預料到 SUPABASE 會出現在這裡,因為它實在是太棒了。 開始使用以下 npm 指令 (Next.js)。 ``` npx create-next-app -e with-supabase ``` 這是使用 supabase 建立用戶的方法。 ``` import { createClient } from '@supabase/supabase-js' // Initialize const supabaseUrl = 'https://chat-room.supabase.co' const supabaseKey = 'public-anon-key' const supabase = createClient(supabaseUrl, supabaseKey) // Create a new user const { user, error } = await supabase.auth.signUp({ email: '[email protected]', password: 'example-password', }) ``` 您可以閱讀[文件](https://supabase.com/docs)。 您可以使用身份驗證、即時、邊緣功能、儲存等功能建立一個速度極快的應用程式。 Supabase 涵蓋了這一切! 他們還提供了一些入門套件,例如 AI 聊天機器人和 Stripe 訂閱。 https://github.com/supabase/supabase --- [11.Refine](https://github.com/refinedev/refine) - 企業開源重組工具。 ------------------------------------------------------------ ![精煉](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qx0kd6t2jzdtf90k5ke3.png) 建立具有無與倫比的靈活性的管理面板、儀表板和 B2B 應用程式 您可以在一分鐘內使用單一 CLI 命令進行設定。 它具有適用於 15 多個後端服務的連接器,包括 Hasura、Appwrite 等。 開始使用以下 npm 指令。 ``` npm create refine-app@latest ``` 這就是使用 Refine 新增登入資訊的簡單方法。 ``` import { useLogin } from "@refinedev/core"; const { login } = useLogin(); ``` 您可以閱讀[文件](https://refine.dev/docs/)。 https://github.com/refinedev/refine --- 12. [Zenstack](https://github.com/zenstackhq/zenstack) - 資料庫到 API 和 UI 只需幾分鐘。 ----------------------------------------------------------------------------- ![禪斯塔克](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3b6n2ea3jeeva6uujoex.png) TypeScript 工具包,透過強大的存取控制層增強 Prisma ORM,並釋放其全端開發的全部功能。 開始使用以下 npx 指令。 ``` npx zenstack@latest init ``` 這是透過伺服器適配器建立 RESTful API 的方法。 ``` // pages/api/model/[...path].ts import { requestHandler } from '@zenstackhq/next'; import { enhance } from '@zenstackhq/runtime'; import { getSessionUser } from '@lib/auth'; import { prisma } from '@lib/db'; // Mount Prisma-style APIs: "/api/model/post/findMany", "/api/model/post/create", etc. // Can be configured to provide standard RESTful APIs (using JSON:API) instead. export default requestHandler({ getPrisma: (req, res) => enhance(prisma, { user: getSessionUser(req, res) }), }); ``` 您可以閱讀[文件](https://zenstack.dev/docs/welcome)。 https://github.com/zenstackhq/zenstack --- 13. [Buildship](https://github.com/rowyio/buildship) - 低程式碼視覺化後端建構器。 -------------------------------------------------------------------- ![建造船](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rzlrynz5xephv4t9layd.png) 對於您正在使用無程式碼應用程式建構器(FlutterFlow、Webflow、Framer、Adalo、Bubble、BravoStudio...)或前端框架(Next.js、React、Vue...)建立的應用程式,您需要一個後端來支援可擴展的 API、安全工作流程、自動化等。BuildShip 為您提供了一種完全視覺化的方式,可以在易於使用的完全託管體驗中可擴展地建立這些後端任務。 這意味著您不需要在雲端平台上爭論或部署東西、執行 DevOps 等。只需立即建置和交付 🚀 https://github.com/rowyio/buildship --- 14. [Taipy](https://github.com/Avaiga/taipy) - 將資料和人工智慧演算法整合到生產就緒的 Web 應用程式中。 ----------------------------------------------------------------------------- ![打字](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ohv3johuz92lsaux52oq.png) Taipy 是一個開源 Python 庫,用於輕鬆的端到端應用程式開發, 具有假設分析、智慧管道執行、內建調度和部署工具。 開始使用以下命令。 ``` pip install taipy ``` 這是一個典型的Python函數,也是過濾器場景中使用的唯一任務。 ``` def filter_genre(initial_dataset: pd.DataFrame, selected_genre): filtered_dataset = initial_dataset[initial_dataset['genres'].str.contains(selected_genre)] filtered_data = filtered_dataset.nlargest(7, 'Popularity %') return filtered_data ``` 您可以閱讀[文件](https://docs.taipy.io/en/latest/)。 他們還有很多可供您建立的[演示應用程式教學](https://docs.taipy.io/en/latest/knowledge_base/demos/)。 https://github.com/Avaiga/taipy --- 15. [LocalForage](https://github.com/localForage/localForage) - 改進了離線儲存。 ------------------------------------------------------------------------ ![當地飼料](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4hlrka5pybvmgmo2djel.png) LocalForage 是一個 JavaScript 函式庫,它透過使用非同步資料儲存和簡單的、類似 localStorage 的 API 來改善 Web 應用程式的離線體驗。它允許開發人員儲存多種類型的資料而不僅僅是字串。 開始使用以下 npm 指令。 ``` npm install localforage ``` 只需包含 JS 檔案並開始使用 localForage。 ``` <script src="localforage.js"></script> ``` 您可以閱讀[文件](https://localforage.github.io/localForage/#installation)。 https://github.com/localForage/localForage --- 16. [Zod](https://github.com/colinhacks/zod) - 使用靜態類型推斷的 TypeScript-first 模式驗證。 ------------------------------------------------------------------------------- ![佐德](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1s6zvmqr0lv93vsrhofs.png) Zod 的目標是透過最大限度地減少重複的類型聲明來對開發人員友好。使用 Zod,您聲明一次驗證器,Zod 將自動推斷靜態 TypeScript 類型。將更簡單的類型組合成複雜的資料結構很容易。 開始使用以下 npm 指令。 ``` npm install zod ``` 這是您在建立字串架構時自訂一些常見錯誤訊息的方法。 ``` const name = z.string({ required_error: "Name is required", invalid_type_error: "Name must be a string", }); ``` 您可以閱讀[文件](https://zod.dev/)。 它適用於 Node.js 和所有現代瀏覽器 https://github.com/colinhacks/zod --- 17.[多普勒](https://github.com/DopplerHQ)- 管理你的秘密。 ----------------------------------------------- ![多普勒](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gycxnuiiwsvibryrytlc.png) 您可以透過在具有開發、暫存和生產環境的專案中組織機密來消除機密蔓延。 開始使用以下指令 (MacOS)。 ``` $ brew install dopplerhq/cli/doppler $ doppler --version ``` 這是安裝 Doppler CLI[的 GitHub Actions 工作流程](https://github.com/DopplerHQ/cli-action)。 您可以閱讀[文件](https://docs.doppler.com/docs/start)。 ``` name: Example action on: [push] jobs: my-job: runs-on: ubuntu-latest steps: - name: Install CLI uses: dopplerhq/cli-action@v3 - name: Do something with the CLI run: doppler secrets --only-names env: DOPPLER_TOKEN: ${{ secrets.DOPPLER_TOKEN }} ``` https://github.com/DopplerHQ --- 18. [FastAPI](https://github.com/tiangolo/fastapi) - 高效能、易於學習、快速編碼、可用於生產。 ------------------------------------------------------------------------- ![快速API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h2awncoia6255ycl95lk.png) FastAPI 是一個現代、快速(高效能)的 Web 框架,用於基於標準 Python 類型提示使用 Python 3.8+ 建立 API。 開始使用以下命令。 ``` $ pip install fastapi ``` 這是您開始使用 FastAPI 的方式。 ``` from typing import Union from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"} @app.get("/items/{item_id}") def read_item(item_id: int, q: Union[str, None] = None): return {"item_id": item_id, "q": q} ``` 您的編輯器將自動完成屬性並了解它們的類型,這是使用 FastAPI 的最佳功能之一。 您可以閱讀[文件](https://fastapi.tiangolo.com/)。 https://github.com/tiangolo/fastapi --- 19. [Flowise](https://github.com/FlowiseAI/Flowise) - 拖放 UI 來建立您的客製化 LLM 流程。 ---------------------------------------------------------------------------- ![流動](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ct732wv07pvwx0nmavp5.png) Flowise 是一款開源 UI 視覺化工具,用於建立客製化的 LLM 編排流程和 AI 代理程式。 開始使用以下 npm 指令。 ``` npm install -g flowise npx flowise start OR npx flowise start --FLOWISE_USERNAME=user --FLOWISE_PASSWORD=1234 ``` 這就是整合 API 的方式。 ``` import requests url = "/api/v1/prediction/:id" def query(payload): response = requests.post( url, json = payload ) return response.json() output = query({ question: "hello!" )} ``` 您可以閱讀[文件](https://docs.flowiseai.com/)。 https://github.com/FlowiseAI/Flowise --- 20. [Scrapy](https://github.com/scrapy/scrapy) - Python 的快速進階網頁爬行和抓取框架.. ------------------------------------------------------------------------ ![鬥志旺盛](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k1b2y1hzdsphw43b6v7b.png) Scrapy 是一個快速的高級網路爬行和網頁抓取框架,用於爬行網站並從頁面中提取結構化資料。它可用於多種用途,從資料探勘到監控和自動化測試。 開始使用以下命令。 ``` pip install scrapy ``` 建造並執行您的網路蜘蛛。 ``` pip install scrapy cat > myspider.py <<EOF import scrapy class BlogSpider(scrapy.Spider): name = 'blogspider' start_urls = ['https://www.zyte.com/blog/'] def parse(self, response): for title in response.css('.oxy-post-title'): yield {'title': title.css('::text').get()} for next_page in response.css('a.next'): yield response.follow(next_page, self.parse) EOF scrapy runspider myspider.py ``` 您可以閱讀[文件](https://scrapy.org/doc/)。 它擁有大約 50k+ 的星星,因此對於網頁抓取來說具有巨大的可信度。 https://github.com/scrapy/scrapy --- 21. [Tone](https://github.com/Tonejs/Tone.js) - 在瀏覽器中製作互動式音樂。 ------------------------------------------------------------- ![音調.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fokxsoblaohgs4tx75g3.png) 開始使用以下 npm 指令。 ``` npm install tone ``` 這是您開始使用 Tone.js 的方法 ``` // To import Tone.js: import * as Tone from 'tone' //create a synth and connect it to the main output (your speakers) const synth = new Tone.Synth().toDestination(); //play a middle 'C' for the duration of an 8th note synth.triggerAttackRelease("C4", "8n"); ``` 您可以閱讀[文件](https://github.com/Tonejs/Tone.js?tab=readme-ov-file#installation)。 https://github.com/Tonejs/Tone.js --- 22. [Spacetime](https://github.com/spencermountain/spacetime) - 輕量級 javascript 時區庫。 ----------------------------------------------------------------------------------- ![時空](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/abfyfuzt4nw4h7b8usab.png) 您可以計算遠端時區的時間;支持夏令時、閏年和半球。按季度、季節、月份、週來定位時間.. 開始使用以下 npm 指令。 ``` npm install spacetime ``` 您可以這樣使用它。 ``` <script src="https://unpkg.com/spacetime"></script> <script> var d = spacetime('March 1 2012', 'America/New_York') //set the time d = d.time('4:20pm') d = d.goto('America/Los_Angeles') d.time() //'1:20pm' </script> ``` https://github.com/spencermountain/spacetime --- 23. [Mermaid](https://github.com/mermaid-js/mermaid) - 從類似 markdown 的文字產生圖表。 ---------------------------------------------------------------------------- ![美人魚](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ggubn86xv7fznxol6fw7.png) 您可以使用 Markdown with Mermaid 等文字產生流程圖或序列圖等圖表。 這就是建立圖表的方法。 ``` sequenceDiagram Alice->>John: Hello John, how are you? loop Healthcheck John->>John: Fight against hypochondria end Note right of John: Rational thoughts! John-->>Alice: Great! John->>Bob: How about you? Bob-->>John: Jolly good! ``` 它將做出如下圖。 ![圖表](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bbuo2ey5q2x3sjwywizg.png) 您可以閱讀[VS Code](https://docs.mermaidchart.com/plugins/visual-studio-code)的[文件](https://mermaid.js.org/intro/getting-started.html)和外掛程式。 請參閱[即時編輯器](https://mermaid.live/edit#pako:eNpVkE1PwzAMhv9KlvM-2AZj62EIxJd24ADXXLzEbaKlcUkdUDX1v5MONomcnNevXz32UWoyKAvZ4mfCoPHRQRWhVuHeO42T7XZHNhTiFb0nMdRjYelbQETRUbpTwRM1uQ2erbaoDyqI_AbnZfjZVZYFVOBCy8J2DWlLwUQHKmAwKrwRo4gnF5Xid-gd2FEAL9hSyp12pMIpNcee2ArxEhH4LG-3D7TPoAPcnhL_4WVxcgHZkfedqIjMSI5ljbEGZ_LyxwFaSbZYo5JFLg3Eg5Iq9NkHiemjC1oWHBOOZWoM8PlQ_8Un45iiLErwbRY9gcH8PUrumuHKlWs5J2oKpasGPUWfZcvctMVsNrSnlWOb9lNN9ax1xkJk-7VZzVaL1RoWS1zdLuFmuTR6P9-sy8X1vDS3V_MFyL7vfwD_bJ1W)中的範例。 https://github.com/mermaid-js/mermaid --- 24.[公共 API](https://github.com/public-apis/public-apis) - 20 多個類別的 1400 多個 API。 ------------------------------------------------------------------------------- ![公共API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sjapk9rwlzdl6bcyqdnl.png) 我們主要使用外部 API 來建立應用程式,在這裡您可以找到所有 API 的清單。網站連結在最後。 它在 GitHub 上擁有大約 279k+ 顆星。 ![公共API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rld5i88smezo1naawz7a.png) 從儲存庫取得網站連結非常困難。所以,我把它貼在這裡。 網址 - [Collective-api.vercel.app/](https://collective-api.vercel.app/) https://github.com/public-apis/public-apis --- 25. [Framer Motion](https://github.com/framer/motion) - 像魔法一樣的動畫。 ----------------------------------------------------------------- ![成幀器運動](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hn4ecqkrhs8f4729bzps.png) 可用的最強大的動畫庫之一。 Framer 使用簡單的聲明性語法意味著您編寫的程式碼更少。更少的程式碼意味著您的程式碼庫更易於閱讀和維護。 您可以建立事件和手勢,並且使用 Framer 的社區很大,這意味著良好的支援。 開始使用以下 npm 指令。 ``` npm install framer-motion ``` 您可以這樣使用它。 ``` import { motion } from "framer-motion" <motion.div whileHover={{ scale: 1.2 }} whileTap={{ scale: 1.1 }} drag="x" dragConstraints={{ left: -100, right: 100 }} /> ``` 您可以閱讀[文件](https://www.framer.com/motion/introduction/)。 https://github.com/framer/motion --- 26.[順便說一句](https://github.com/btw-so/btw)- 在幾分鐘內建立您的個人部落格。 ---------------------------------------------------------- ![順便提一句](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gnne3lrfpolotmxkdz2m.png) 順便說一句,您可以註冊並使用,而無需安裝任何東西。您也可以使用開源版本自行託管。 ![順便提一句](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2rli7hpoccqwpvba29b4.png) 使用順便說一句建立的[範例部落格](https://www.siddg.com/about)。 https://github.com/btw-so/btw --- 27. [Formbricks](https://github.com/formbricks/formbricks) - 開源調查平台。 -------------------------------------------------------------------- ![成型磚](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tp6ggyom33vdifd3m1vt.png) Formbricks 提供免費、開源的測量平台。透過精美的應用程式內、網站、連結和電子郵件調查收集用戶旅程中每個點的回饋。在 Formbricks 之上建置或利用預先建置的資料分析功能。 開始使用以下 npm 指令。 ``` npm install @formbricks/js ``` 這就是您開始使用 formbricks 的方法。 ``` import formbricks from "@formbricks/js"; if (typeof window !== "undefined") { formbricks.init({ environmentId: "claV2as2kKAqF28fJ8", apiHost: "https://app.formbricks.com", }); } ``` 您可以閱讀[文件](https://formbricks.com/docs/getting-started/quickstart-in-app-survey)。 https://github.com/formbricks/formbricks --- 28. [Stripe](https://github.com/stripe) - 支付基礎設施。 ------------------------------------------------- ![條紋](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/79yvcgsi4744cmryh15j.png) 數以百萬計的各種規模的公司在線上和親自使用 Stripe 來接受付款、發送付款、自動化財務流程並最終增加收入。 開始使用以下 npm 指令 (React.js)。 ``` npm install @stripe/react-stripe-js @stripe/stripe-js ``` 這就是使用鉤子的方法。 ``` import React, {useState} from 'react'; import ReactDOM from 'react-dom'; import {loadStripe} from '@stripe/stripe-js'; import { PaymentElement, Elements, useStripe, useElements, } from '@stripe/react-stripe-js'; const CheckoutForm = () => { const stripe = useStripe(); const elements = useElements(); const [errorMessage, setErrorMessage] = useState(null); const handleSubmit = async (event) => { event.preventDefault(); if (elements == null) { return; } // Trigger form validation and wallet collection const {error: submitError} = await elements.submit(); if (submitError) { // Show error to your customer setErrorMessage(submitError.message); return; } // Create the PaymentIntent and obtain clientSecret from your server endpoint const res = await fetch('/create-intent', { method: 'POST', }); const {client_secret: clientSecret} = await res.json(); const {error} = await stripe.confirmPayment({ //`Elements` instance that was used to create the Payment Element elements, clientSecret, confirmParams: { return_url: 'https://example.com/order/123/complete', }, }); if (error) { // This point will only be reached if there is an immediate error when // confirming the payment. Show error to your customer (for example, payment // details incomplete) setErrorMessage(error.message); } else { // Your customer will be redirected to your `return_url`. For some payment // methods like iDEAL, your customer will be redirected to an intermediate // site first to authorize the payment, then redirected to the `return_url`. } }; return ( <form onSubmit={handleSubmit}> <PaymentElement /> <button type="submit" disabled={!stripe || !elements}> Pay </button> {/* Show error message to your customers */} {errorMessage && <div>{errorMessage}</div>} </form> ); }; const stripePromise = loadStripe('pk_test_6pRNASCoBOKtIshFeQd4XMUh'); const options = { mode: 'payment', amount: 1099, currency: 'usd', // Fully customizable with appearance API. appearance: { /*...*/ }, }; const App = () => ( <Elements stripe={stripePromise} options={options}> <CheckoutForm /> </Elements> ); ReactDOM.render(<App />, document.body); ``` 您可以閱讀[文件](https://github.com/stripe/react-stripe-js?tab=readme-ov-file#minimal-example)。 您幾乎可以整合任何東西。它有一個巨大的選項清單。 ![整合](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/67f3pb2i8xolt635rp2p.png) https://github.com/stripe --- 29. [Upscayl](https://github.com/upscayl/upscayl) - 開源 AI 影像升級器。 ---------------------------------------------------------------- ![高級](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2c1837rev5jb260ro2sd.png) 適用於 Linux、MacOS 和 Windows 的免費開源 AI Image Upscaler 採用 Linux 優先概念建構。 它可能與全端無關,但它對於升級圖像很有用。 ![高級](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a4qq1wm3wey3vihn9al4.png) 透過最先進的人工智慧,Upscayl 可以幫助您將低解析度影像變成高解析度。清脆又鋒利! https://github.com/upscayl/upscayl --- 30.[重新發送](https://github.com/resend)- 為開發人員提供的電子郵件 API。 ------------------------------------------------------- ![重發](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x3auhh3hbxjmmzehe5v0.png) 您可以使用 React 建立和傳送電子郵件。 2023 年最受炒作的產品之一。 開始使用以下 npm 指令。 ``` npm install @react-email/components -E ``` 這是將其與 next.js 專案整合的方法。 ``` import { EmailTemplate } from '@/components/email-template'; import { Resend } from 'resend'; const resend = new Resend(process.env.RESEND_API_KEY); export async function POST() { const { data, error } = await resend.emails.send({ from: '[email protected]', to: '[email protected]', subject: 'Hello world', react: EmailTemplate({ firstName: 'John' }), }); if (error) { return Response.json({ error }); } return Response.json(data); } ``` 您可以閱讀[文件](https://resend.com/docs/introduction)。 ![重發](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rer9ym187e4i9l11afkg.png) 基本概念是一個簡單、優雅的介面,讓您可以在幾分鐘內開始發送電子郵件。它可以透過適用於您最喜歡的程式語言的 SDK 直接融入您的程式碼中。 https://github.com/resend --- 哇!如此長的專案清單。 我知道您有更多想法,分享它們,讓我們一起建造:D 如今建立全端應用程式並不難,但每個應用程式都可以透過有效地使用優秀的開源專案來解決任何問題來增加這一獨特因素。 例如,您可以建立一些提供通知或建立 UI 流來抓取資料的東西。 我希望其中一些內容對您的開發之旅有用。他們擁有一流的開發人員經驗;你可以依賴他們。 由於您將要建造東西,因此您可以在這裡找到一些[瘋狂的想法](https://github.com/florinpop17/app-ideas)。 祝你有美好的一天!直到下一次。 --- 原文出處:https://dev.to/copilotkit/im-building-a-full-stack-app-here-are-the-libraries-im-going-to-use-51nk

軟體工程師面試學習指南

[本·羅戈揚](https://www.linkedin.com/in/benjaminrogojan/) 軟體工程面試與其他技術面試一樣,需要充分的準備。有許多主題需要涵蓋,以確保您準備好應對有關演算法、資料結構、設計、最佳化以及不斷增長的主題的連續問題。 因此,我在最後一輪面試中建立了一個清單,涵蓋了許多熱門話題。 為了幫助您追蹤進度,我們針對下面列出的相同問題編制了一份全面的清單; [該列表可以在這裡找到](https://docs.google.com/spreadsheets/d/19hSRrL4l3gRiJ5ucH9q4iwFo2QHgic9gGMNUrcn1mm0/edit?usp=sharing)。 ### **聆聽經典熱身** 1. [fizzbuzz](https://www.hackerrank.com/challenges/fizzbuzz/problem) 2. [子陣列和等於 K](https://leetcode.com/problems/subarray-sum-equals-k/) 3. [陣列:左旋轉](https://www.hackerrank.com/challenges/ctci-array-left-rotation/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays) 4. [字串:製作字謎詞](https://www.hackerrank.com/challenges/ctci-making-anagrams/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=strings) 5. [第 N 次斐波那契數](https://www.algoexpert.io/questions/Nth%20Fibonacci) 你怎麼做的?花點時間對這些經典作品進行評價。我們在面試過程中的某個時刻被問到了其中大部分問題,而且通常是在早期就被問到的淘汰式問題。它們通常與演算法和資料結構關係不大,但仍然需要對循環和陣列有很好的理解(是的,陣列是一種資料結構)。 ### **演算法和資料結構** #### **預習問題** 在觀看有關資料結構和演算法的影片內容之前,請考慮嘗試以下這些問題。看看你能否回答他們。這將幫助您知道要關注什麼。 1. [985. 查詢後偶數之和](https://leetcode.com/problems/sum-of-even-numbers-after-queries/) 2. [657. 機器人回歸原點](https://leetcode.com/problems/robot-return-to-origin/) 3. [961. 2N 陣列中的 N 重複元素](https://leetcode.com/problems/n-repeated-element-in-size-2n-array/) 4. [110.平衡二元樹](https://leetcode.com/problems/balanced-binary-tree/) 5. [3. 最長無重複字元的子字串](https://leetcode.com/problems/longest-substring-without-repeating-characters/) 6. [19. 從清單結尾刪除第 N 個節點](https://leetcode.com/problems/remove-nth-node-from-end-of-list/) 7. [23. 合併 k 個排序列表](https://leetcode.com/problems/merge-k-sorted-lists/) 8. [31. 下一個排列](https://leetcode.com/problems/next-permutation/) ### 演算法和資料結構影片 #### 資料結構 ![](https://cdn-images-1.medium.com/max/1600/1*Dyu63sMUVL-gYEZISOE2BQ.jpeg) 1. [資料結構與演算法 #1 --- 什麼是資料結構?](https://www.youtube.com/watch?v=bum_19loj9A) --- 影片 2. [多調光](https://archive.org/details/0102WhatYouShouldKnow/02_05-multidimensionalArrays.mp4)--- 影片 3. [動態陣列](https://www.coursera.org/learn/data-structures/lecture/EwbnV/dynamic-arrays)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 4. [調整陣列大小](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 5. [資料結構:鍊錶](https://youtu.be/njTh_OwMljA)--- 影片 6. [核心鍊錶與陣列](https://www.coursera.org/learn/data-structures-optimizing-performance/lecture/rjBs9/core-linked-lists-vs-arrays)--- 影片 7. [指針到指針](https://www.eskimo.com/~scs/cclass/int/sx8.html)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 8. [資料結構:樹](https://youtu.be/oSWTXtMglKE)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 9. [資料結構:堆](https://youtu.be/t0Cq6tVNRBA)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 10. [資料結構:哈希表](https://youtu.be/shs0KM3wKv8)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 11. [電話簿問題](https://www.coursera.org/learn/data-structures/lecture/NYZZP/phone-book-problem)---影片 12. [資料結構:堆疊和佇列](https://youtu.be/wjI1WNcIntg)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 13. [使用堆疊後進先出](https://archive.org/details/0102WhatYouShouldKnow/05_01-usingStacksForLast-inFirst-out.mp4)--- 影片 14. [資料結構:計算機科學速成課程#14](https://youtu.be/DuDz6B4cqVc)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 15. [資料結構:嘗試](https://www.youtube.com/watch?v=zIjfhVPRZCg)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 #### 演算法 ![](https://cdn-images-1.medium.com/max/1600/1*bPpvELo9_QqQsDz7CSbwXQ.gif) 1. [演算法:圖搜尋、DFS 和 BFS](https://www.youtube.com/watch?v=zaBhtODEL0w&list=PLX6IKgS15Ue02WDPRCmYKuZicQHit9kFt)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 2. [BFS(廣度優先搜尋)和DFS(深度優先搜尋)](https://www.youtube.com/watch?v=uWL6FJhq5fM) --- 影片 3. [演算法:二分查找](https://youtu.be/P3YID7liBug)---影片 4. [二元搜尋樹回顧](https://www.youtube.com/watch?v=x6At0nzX92o&index=1&list=PLA5Lqm4uh9Bbq-E0ZnqTIa8LRaL77ica6)--- 影片 5. [用於面試的 Python 演算法](https://www.youtube.com/watch?v=p65AHm9MX80)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 6. [演算法:遞歸](https://youtu.be/KEEKn7Me-ms)---影片 7. [演算法:冒泡排序](https://youtu.be/6Gv8vg0kcHc)--- 影片 8. [演算法:歸併排序](https://youtu.be/KF2j-9iSf4Q)--- 影片 9. [演算法:快速排序](https://youtu.be/SLauY6PpjW4)---影片 ### **大 O 表示法** 1. [大 O 表示法與時間複雜度簡介(資料結構與演算法 #7)](https://www.youtube.com/watch?v=D6xkbGLQesk) --- 影片 2. [哈佛 CS50 --- 漸近符號](https://www.youtube.com/watch?v=iOq5kSKqeR4)--- 影片 3. [演算法複雜度分析的簡單介紹](http://discrete.gr/complexity/)--- Post 4. [備忘錄](http://bigocheatsheet.com/)--- 帖子 ### **動態規劃** 1. [動態規劃(像程式設計師一樣思考)---影片](https://www.youtube.com/watch?v=iv_yHjmkv4I) 2. [演算法:記憶化與動態規劃 --- 影片](https://www.youtube.com/watch?v=P8Xa2BitN3I&t=13s) 3. 6 [.006:動態規劃 I:斐波那契、最短路徑 --- 影片](https://www.youtube.com/watch?v=OQ5jsbhAv_M&t=7s) 4. [6.006:動態規劃 II:文字對齊、二十一點 --- 影片](https://www.youtube.com/watch?v=ENyox7kNKeY&t=4s) 5. [動態規劃 --- 帖子](https://www.topcoder.com/community/competitive-programming/tutorials/dynamic-programming-from-novice-to-advanced/) ### **字串操作** 1. [編碼面試問答:最長的連續字元](https://www.youtube.com/watch?v=qRNB8CV3_LU)--- 影片 2. [Sedgewick --- 子字串搜尋](https://www.coursera.org/learn/algorithms-part2/home/week/4)--- 影片 #### 面試問題演練 1. [谷歌編碼面試 --- 普世價值樹問題](https://www.youtube.com/watch?v=7HgsS8bRvjo)--- 影片 2. [Google 編碼面試問題和答案 #1:第一個重複出現的字元](https://www.youtube.com/watch?v=GJdiM-muYqc)--- 影片 3. [在二元搜尋樹中找到最小和最大元素](https://www.youtube.com/watch?v=Ut90klNN264&index=30&list=PL2_aWCzGMAwI3W_JlcBbtYTwiQSsOTa6P)--- 影片 4. [求二元樹的高度](https://www.youtube.com/watch?v=_pnqMz5nrRs&list=PL2_aWCzGMAwI3W_JlcBbtYTwiQSsOTa6P&index=31)--- 影片 5. [檢查二元樹是否為二元搜尋樹](https://www.youtube.com/watch?v=yEwSGhSsT0U&index=35&list=PL2_aWCzGMAwI3W_JlcBbtYTwiQSsOTa6P)--- 影片 6. [什麼是尾遞歸?為什麼這麼糟?](https://www.quora.com/What-is-tail-recursion-Why-is-it-so-bad) --- 影片 ### **學後問題** 現在您已經學習了一些,並觀看了一些影片,讓我們嘗試更多問題! 1. [越大越好](https://www.hackerrank.com/challenges/bigger-is-greater/problem) 2. [6.之字折線轉換](https://leetcode.com/problems/zigzag-conversion/) 3. [7. 反轉整數](https://leetcode.com/problems/reverse-integer/) 4. [40. 組合和 II](https://leetcode.com/problems/combination-sum-ii/) 5. [43. 字串相乘](https://leetcode.com/problems/multiply-strings/) 6. [拉里的陣列](https://www.hackerrank.com/challenges/larrys-array/problem) 7. [短回文](https://www.hackerrank.com/challenges/short-palindrome/problem) 8. [65. 有效號碼](https://leetcode.com/problems/valid-number/) 9. [越大越好](https://www.hackerrank.com/challenges/bigger-is-greater/problem) 10. [完整計數排序](https://www.hackerrank.com/challenges/countingsort4/problem) 11. [莉莉的家庭作業](https://www.hackerrank.com/challenges/lilys-homework/problem) 12. [普通孩子](https://www.hackerrank.com/challenges/common-child/problem) 13. [459. 重複子字串模式](https://leetcode.com/problems/repeated-substring-pattern/) 14. [27. 刪除元素](https://leetcode.com/problems/remove-element/) 15. [450. 刪除 BST 中的節點](https://leetcode.com/problems/delete-node-in-a-bst/) 16. [659. 將陣列分割成連續的子序列](https://leetcode.com/problems/split-array-into-consecutive-subsequences/) 17. [最大值有界的子陣列數](https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum) 18. [組合和 IV](https://leetcode.com/problems/combination-sum-iv) 19. [買賣股票的最佳時機(有冷卻時間)](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown) 20. [最長重複字元替換](https://leetcode.com/problems/longest-repeating-character-replacement) 21. [成對交換節點](https://leetcode.com/problems/swap-nodes-in-pairs) 22. [二元樹右側視圖](https://leetcode.com/problems/binary-tree-right-side-view) 23. [展平嵌套列表迭代器](https://leetcode.com/problems/flatten-nested-list-iterator) 24. [二元樹層次順序遍歷](https://leetcode.com/problems/binary-tree-level-order-traversal) 25. [二元搜尋樹迭代器](https://leetcode.com/problems/binary-search-tree-iterator) 26. [對鏈最大長度](https://leetcode.com/problems/maximum-length-of-pair-chain) 27. [將鍊錶拆分為多個部分](https://leetcode.com/problems/split-linked-list-in-parts) ### **操作性程式設計問題** 有些公司不會問你演算法問題。相反,他們可能會更專注於實施和營運問題。這些通常更小眾,涉及實際問題,例如循環資料和執行某種任務。這些類型的問題通常不需要太多練習,因為更多的是了解陣列和 HashMap 等基本概念並追蹤您對它們所做的事情。 1. [袋鼠問題](https://www.hackerrank.com/challenges/kangaroo/problem) 2. [打破記錄](https://www.hackerrank.com/challenges/breaking-best-and-worst-records/problem) 3. [查找字串](https://www.hackerrank.com/challenges/find-a-string/problem)[迭代器](https://www.hackerrank.com/challenges/itertools-permutations/problem) 4. [不知道!](https://www.hackerrank.com/challenges/no-idea/problem) 5. [程式設計師的日子](https://www.hackerrank.com/challenges/day-of-the-programmer/problem) 6. [排行榜](https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem) 7. [詞序](https://www.hackerrank.com/challenges/word-order/problem) 8. [夏洛克和方塊](https://www.hackerrank.com/challenges/sherlock-and-squares/problem) 9. [均衡陣列](https://www.hackerrank.com/challenges/equality-in-a-array/problem) 10. [蘋果和橘子](https://www.hackerrank.com/challenges/apple-and-orange/problem) 11. [更多操作風格問題](https://www.hackerrank.com/domains/python) ### **系統設計影片** 系統設計問題是至關重要的問題,表明您不僅僅是一名編碼員。身為工程師,您需要能夠思考大局。某些服務屬於哪裡,您需要什麼樣的伺服器,您將如何管理流量等等。所有這些想法都表明您能夠設計軟體,而不僅僅是編寫人們告訴您編寫的程式碼。 1. [停車場系統](https://youtu.be/DSGsa0pu8-k)---影片 2. [什麼是應用程式](https://www.youtube.com/watch?v=vvhC64hQZMk)--- 影片 3. [優步設計](https://youtu.be/umWABit-wbk)---影片 4. [Instagram](https://www.youtube.com/watch?v=QmX2NPkJTKg) --- 影片 5. [Tinder 服務](https://www.youtube.com/watch?v=xQnIN9bW0og)--- 影片 ### **作業系統** 作業系統問題比較少見,但是對執行緒、調度、記憶體等概念有紮實的理解是有好處的,即使只是基本的理解。當被問到進程和線程有什麼區別而不知道答案時,這是非常尷尬的。 1. [常見作業系統面試問題](https://www.geeksforgeeks.org/commonly-asked-operating-systems-interview-questions-set-1/) 2. [什麼是翻譯後備緩衝區?](https://www.geeksforgeeks.org/operating-system-translation-lookaside-buffer-tlb/) 3. [為什麼循環法可以避免優先反轉問題?](https://leetcode.com/discuss/interview-question/operating-system/220604/Why-does-Round-Robin-avoid-the-Priority-Inversion-Problem) 4. [中斷與系統呼叫---檔案系統中的「inode」是什麼?](https://leetcode.com/discuss/interview-question/operating-system/124838/Interrupt-Vs-System-Call) 5. [作業系統面試題目及答案 --- 第一部分](https://www.youtube.com/watch?v=b18X4uOKjHs) 6. [什麼是內核 --- Gary 解釋](https://www.youtube.com/watch?v=mycVSMyShk8) 7. [循環演算法教程(CPU調度)](https://www.youtube.com/watch?v=aWlQYllBZDs) 8. [LRU 快取的魔力(Google 開發 100 天)](https://www.youtube.com/watch?v=R5ON3iwx78M) --- 影片 9. [MIT 6.004 L15:記憶體層次結構](https://www.youtube.com/watch?v=vjYF_fAZI5E&list=PLrRW1w6CGAcXbMtDFj205vALOGmiRc82-&index=24)--- 影片 10. [中斷](https://www.youtube.com/watch?v=uFKi2-J-6II&list=PLCiOXwirraUCBE9i_ukL8_Kfg6XNv7Se8&index=3)---影片 11. [調度](https://www.youtube.com/watch?v=-Gu5mYdKbu4&index=4&list=PLCiOXwirraUCBE9i_ukL8_Kfg6XNv7Se8)---影片 ### **執行緒數** ![](https://cdn-images-1.medium.com/max/1600/1*uSHd3KSxg363C1frMv2KwQ.png) 1. [用戶級線程與內核級線程](https://leetcode.com/discuss/interview-question/operating-system/124631/User-Level-thread-Vs-Kernel-Level-thread) 2. [行程和線程簡介](https://www.youtube.com/watch?v=exbKr6fnoUw)--- 影片 3. [進程和線程之間的區別 --- 佐治亞理工學院 --- 高級操作系統](https://www.youtube.com/watch?v=O3EyzlZxx3g&t=11s)--- 影片 4. [分叉和多線程之間的區別](https://leetcode.com/discuss/interview-question/operating-system/125024/Difference-between-forking-and-multithreading) ### **物件導向** ![](https://cdn-images-1.medium.com/max/1600/1*8LHiDwWhrU4iegYiNnKX_A.png) 與作業系統類似,並不是每次面試都會問你有關物件導向程式設計的問題,但你永遠不知道。您需要確保記住計算機 162 課程中的基礎知識。 1. [Java 程式設計教學 --- 49 --- 繼承](https://www.youtube.com/watch?v=9JpNY-XAseg)--- 影片 2. [Java 程式設計教學 --- 55 --- 多態性簡介](https://www.youtube.com/watch?v=0xw06loTm1k)--- 影片 3. [Java 程式設計教學 --- 58 --- 抽象類別與具體類別](https://www.youtube.com/watch?v=TyPNvt6Zg8c)--- 影片 4. [Java 程式設計教學 --- 57 --- 重寫規則](https://www.youtube.com/watch?v=zN9pKULyoj4&t=3s)--- 影片 5. [Java 程式設計教學 --- 59 --- 保存物件的類](https://www.youtube.com/watch?v=slY5Ag7IjM0) 6. [物件導向程式設計](https://www.youtube.com/watch?v=lbXsrHGhBAU)---影片 ### **設計模式** 如果您像我們一樣,我們不會被教導所有各種設計模式。因此,最好了解它們的工作原理以及使用它們的原因。一些面試問題可以很簡單,例如“為什麼要使用工廠類?” 1. [工廠設計模式](https://www.youtube.com/watch?v=ub0DXaeV6hA)---影片 2. [觀察者設計模式](https://youtu.be/wiQdrH2YpT4)---影片 3. [適配器設計模式](https://www.youtube.com/watch?v=qG286LQM6BU&list=PLF206E906175C7E07&index=13)---影片 4. [立面設計模式](https://www.youtube.com/watch?v=B1Y8fcYrz5o&list=PLF206E906175C7E07&index=14)---影片 5. [責任鏈設計模式](https://www.youtube.com/watch?v=jDX6x8qmjbA&list=PLF206E906175C7E07&index=22)---影片 6. [解譯器設計模式](https://www.youtube.com/watch?v=6CVymSJQuJE&list=PLF206E906175C7E07&index=23)---影片 7. [單例設計模式教學](https://www.youtube.com/watch?v=NZaXM67fxbs&list=PLF206E906175C7E07&index=7)--- 影片 8. [第 6 章(第 1 部分)--- 模式(影片)](https://youtu.be/LAP2A80Ajrg?list=PLJ9pm_Rc9HesnkwKlal_buSIHA-jTZMpO&t=3344) --- 影片 9. [Head First 設計模式](https://www.amazon.com/Head-First-Design-Patterns-Freeman/dp/0596007124)--- 影片 ### SQL 這是最後一節。你們中的許多人可能不會被問到那麼多 SQL 問題。不過,我始終認為放在後口袋是件好事。 #### SQL --- 問題 1. [262. 行程和用戶](https://leetcode.com/problems/trips-and-users/) 2. [601. 體育場人流量](https://leetcode.com/problems/human-traffic-of-stadium/) 3. [185. 部門前三薪資](https://leetcode.com/problems/department-top-three-salaries/) 4. [626.交換席位](https://leetcode.com/problems/exchange-seats/) 5. [駭客排名報告](https://www.hackerrank.com/challenges/the-report/problem) 6. [177.第N最高薪水](https://leetcode.com/problems/nth-highest-salary/) 7. [對稱對](https://www.hackerrank.com/challenges/symmetric-pairs/problem) 8. [職業](https://www.hackerrank.com/challenges/placements/problem)[安置](https://www.hackerrank.com/challenges/occupations/problem) 9. [奧利凡德的庫存](https://www.hackerrank.com/challenges/harry-potter-and-wands/problem) #### SQL --- 影片 1. [IQ15:6 個 SQL 查詢面試問題](https://www.youtube.com/watch?v=uAWWhEA57bE)--- 影片 2. [了解 ROW\_NUMBER 和分析函數](https://www.youtube.com/watch?v=QFj-hZi8MKk)--- 影片 3. [分析函數的高級實現](https://www.youtube.com/watch?v=G3kYPzLWtpo&t=4s)--- 影片 4. [分析函數的高級實現第 2 部分](https://www.youtube.com/watch?v=XecU6Ieyu-4&t=54s)--- 影片 5. [聰明的貓頭鷹 SQL 影片](https://www.youtube.com/watch?v=2-1XQHAgDsM&list=PL6EDEB03D20332309)--- 影片 #### SQL 後問題 1. [二元樹節點](https://www.hackerrank.com/challenges/binary-search-tree-1/problem) 2. [氣象觀測站 18](https://www.hackerrank.com/challenges/weather-observation-station-18/problem) 3. [挑戰](https://www.hackerrank.com/challenges/challenges/problem)[列印素數](https://www.hackerrank.com/challenges/print-prime-numbers/problem) 4. [595.大國](https://leetcode.com/problems/big-countries/) 5. [626.交換席位](https://leetcode.com/problems/exchange-seats/) 6. [SQL 面試問題:3 個技術篩選練習(針對資料分析師)](https://data36.com/sql-interview-questions-tech-screening-data-analysts/) 面試可能會很困難,因為你會覺得自己沒有任何進展。擁有本學習指南將幫助您追蹤您的進度並讓您更好地了解自己的表現! 祝你好運! 另外,如果您想閱讀/觀看更多精彩的貼文或影片: [在 SaturnCloud 上使用 Jupyter Notebook 連接到大查詢第 2 部分](https://www.youtube.com/watch?v=O1cBN5gJtdw&t=15s) [身為資料科學家你應該閱讀的三本書](https://www.coriers.com/three-books-you-must-read-if-you-want-a-career-as-a-data-scientist/) [Hadoop 與關聯式資料庫](http://www.acheronanalytics.com/acheron-blog/hadoop-vs-relational-databases) [算法如何變得不道德和有偏見](http://www.acheronanalytics.com/acheron-blog/how-do-machines-learn-bias-data-science) [如何改善資料驅動策略](http://www.acheronanalytics.com/acheron-blog/how-to-improve-your-data-driven-strategy) [如何開發穩健演算法](https://medium.com/better-programming/how-to-develop-a-robust-algorithm-c38e08f32201) [資料科學家必須具備的 4 項技能](https://www.theseattledataguy.com/4-skills-data-scientist-must-have/) [SQL 最佳實踐 - 設計 ETL 影片](http://www.acheronanalytics.com/acheron-blog/sql-best-practices-designing-an-etl-video) --- 原文出處:https://dev.to/seattledataguy/the-interview-study-guide-for-software-engineers-764

酷炫的個人網站,以及製作方法說明

對於未來的軟體工程師、設計師或產品經理來說,個人網站幾乎和履歷一樣成為標準——這是有充分理由的。個人網站是展示技術或設計悟性的好方法,並提供比標準簡歷更個性化和有趣的格式(而且您無論如何都可以將簡歷放在您的網站上)。網站比一張紙更具互動性,會讓您脫穎而出,並開啟潛在的對話主題。建立個人網站的方法有很多種,您應該仔細考慮您的方法——這將是您在網路上向招聘人員和許多臨時谷歌或linkedin搜尋者展示的方式。 接下來,我們將看看特別令人難忘的個人網站(前面很漂亮),並提供一些建立或更新您自己的網站的建議。 ### 個人網站的不同用途 個人網站可以實現許多不同的目的。我已經介紹了下面一些較大的類別。 #### 資料夾 對於藝術家或設計師來說,個人網站可以作為您的作品集。這是一種很棒的格式,並且很容易保持最新狀態。例如,考慮一下自由插畫家 Paddy Donnelly 的這個[網站](http://lefft.com/)。打開這些網站以獲得完整的體驗。 ![](https://thepracticaldev.s3.amazonaws.com/i/q2gq0m32cnjf6bv6soqf.png) #### 履歷 從最基本的形式來看,個人網站是讓您的履歷變得更有趣的好方法。即使從紙質簡歷中取出文字並在帶有電子郵件連結的網站上很好地格式化它也是一個很好的開始。例如,Jackie Luo 在她的[網站](http://jackieluo.com/)上提供了她簡歷的可讀版本。 ![](https://thepracticaldev.s3.amazonaws.com/i/4ylsr3ybq8azb3p49mlo.png) #### 以我為中心 即使您不想展示您的專業經驗,個人網站也是集中搜尋有關您自己的資訊的好方法。許多人在其網站上提供社交媒體帳戶的連結。例如,Safia Abdella 的[網站](https://safia.rocks/)乾淨、簡單,可以輕鬆存取造訪她網站的任何人可能需要的關鍵資訊。 ![](https://thepracticaldev.s3.amazonaws.com/i/mfg6uhfd1zwteo422d71.jpg) #### 部落格 個人網站是保存部落格的好地方,這是向訪客展示您的作品的好方法。阿萊娜·卡夫克斯 (Alaina Kafkes) 除了在 dev.to 和 Medium 上提供她的個人資料連結之外,還提供她[網站](http://alainakafk.es/#/words)上所有最新內容的連結。 ![](https://thepracticaldev.s3.amazonaws.com/i/9fsaresu0saxr195mwgm.png) #### 其他的東西 向網路講述您的故事。履歷、社群媒體資料,甚至你的 Facebook 頁面都受到相當嚴格的控制。網站是一個可以是任何你喜歡的空間:一個遊戲化的仙境,最少的描述,或其他什麼。考慮一下 Robby Leonardi 屢獲殊榮的遊戲化簡歷[網站](http://www.rleonardi.com/interactive-resume/)。 ![](https://thepracticaldev.s3.amazonaws.com/i/j69t5vlmeani2k8a67w3.png) ### 整個職業生涯中的個人網站 如果您是應屆畢業生或正在進行職業轉型,個人網站對技術招募人員來說會很有吸引力。早在 2013 年,《富比士》就報導稱,56% 的招募經理表示,與其他品牌工具相比,他們對候選人的個人網站印象更深刻。 作為未來的設計師或軟體工程師,您可以在頁面上展示您的技術能力!即使你不做技術性的事情,網站也比紙質簡歷更引人注目、更個性化,所以這是一個很好的方法,可以通過簡單的“在i-am-the-bomb.com 查看我的簡歷」來獲得優勢。 」。 當您繼續您的職業生涯時,您仍然可以保留個人網站來展示您正在從事的工作並維護您的個人品牌。例如,Cassidy Williams 在她的[網站](http://cassidoo.co/)上提供了有關她所做的事情的更新時間表。 ![](https://thepracticaldev.s3.amazonaws.com/i/9xnfkmkgtfi48c0id89b.png) 如果您正在尋找寫作和演講的機會,這是一個很好的地方,可以展示您的所作所為,並向在線查找您的任何人提供可存取的資訊。 隨著時間的推移維護您的網站可以讓您在開始另一次求職時輕鬆地短暫刷新,這也是吸引不可預見的機會和聯繫的好方法。我曾經有一個我不認識的表弟透過個人網站聯絡我——你永遠不知道! ### 入門 現在製作網站比以往任何時候都容易。那裡有一些很棒的入門教程。如果您想快速入門,我推薦[WordPress](http://www.wpbeginner.com/guides/)或[SquareSpace](https://developers.squarespace.com/beginner-tutorial/)的這些教學。如果您想建立和託管自己的, [Github Pages](https://guides.github.com/features/pages/)中的本指南是一個很好的起點。如果您想深入了解建置、託管和服務,這是一個很好的學習方式!以下是一些可能有用的資源: - MEAN 入門網站[儲存庫](https://github.com/manishrw/mean-starter-website) - Jekyll 入門套件儲存[庫](https://github.com/nirgn975/generator-jekyll-starter-kit) - Github 自己的 Web Starter it[儲存庫](https://github.com/google/web-starter-kit) - 關於工具和框架的[實用開發線程](https://dev.to/nayeonkim/what-toolframeworkcmsetc-do-you-use-to-build-your-own-personal-website) - 與實用開發文章相對應的[Twitter 線程](https://twitter.com/thepracticaldev/status/894161129492156416) ### 一般建議 1. **從某個地方開始。**人們很容易對一個網站感到興奮,努力獲取域名,將其加入到您的個人簡介中,在頁面上貼上“正在進行中”的標籤,然後完全忘記它。當我點擊某人的個人網站時,大約有 10-20% 的時間,該網站要么完全關閉,要么「正在進行」數月或數年。不要被所有令人驚嘆的網站嚇倒。作為一個初學者,至少要在大文本中加入指向您的相關帳戶和您的姓名的連結 - 這比看起來像一個無法完成他們開始的事情要好得多。 2. 從所有可能看到的人的角度**來批判性地審視您在網站上放置的內容**。雖然 Twitter 和 linkedin 帳戶很棒,但如果您不希望招聘人員看到您的 tumblr 頁面上有關野貓的訊息,請不要將其連結到那裡。同樣,如果你認為你的黑客馬拉松專案在更好的Tinder 上對公司來說看起來很棒,但可能會讓你的父母不高興,那麼你可以將你的個人網站從你的Facebook 公開資料中刪除。有時我們都可以提醒網路是公共的! 3. **並非您的所有作品都需要展示。**個人網站可以是展示您早期專案的有趣方式,儘管您在七年級製作的海報可能會讓您感到溫暖和懷舊,但它可能會引起招聘人員的懷疑。選擇最能展現你的作品。 4. **讓它個性化。**這是您的個人網站是有原因的。不要害怕在你的網站上放一些東西。例如,Terri Burns 在她的[網站](http://tcburning.com/)上分享了她的興趣的隨機集合。這樣的事情會讓招募人員對你更有興趣,並且讓其他網站追蹤你的人也能了解你的興趣! ![](https://thepracticaldev.s3.amazonaws.com/i/cc0my10l8i7bw6yqi4cn.png) 5. 發揮創意。更多激發您創造力的好點子: - 艾伯塔德沃爾 (Alberta Devor) 的火車路線靈感[網站](https://albertadevor.com/) ![](https://thepracticaldev.s3.amazonaws.com/i/m4kry69flr4l8t2kjq8i.png) - 像素獎得主 Maria Passo 製作的精美動畫[網站](http://marisapassos.com/) ![](https://thepracticaldev.s3.amazonaws.com/i/gazd8zmp2c4clff2u59b.png) - 加里·勒馬森 (Gary Le Masson)[網站](http://www.garylemasson.com/)上引人注目的搜尋引擎框 ![](https://thepracticaldev.s3.amazonaws.com/i/f406l7g0g7q05wzt1l63.png) - Kristine Flatland 格式有趣的[網站](http://kristineflat.land/#work2) ![](https://thepracticaldev.s3.amazonaws.com/i/e8ireutjnslih5n49vln.png) - 克萊門汀‧雅各比 (Clementine Jacoby) 繪製的她曾經造訪過的[網站](http://clementinejacoby.com/new_map.html)的地圖 ![](https://thepracticaldev.s3.amazonaws.com/i/le35y2tqg55xdsdt3yls.png) 在評論中分享在您的網站上對您有用的內容! --- 原文出處:https://dev.to/amandasopkin/fantastic-personal-websites-and-how-to-make-them--22om

為初學者到專家提供的 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