天天看點

一口氣最全解讀ChatGPT程式設計超能力,13個章50個執行個體,小白也能懂

前言

今天,我們通過十三個章節,50+個示例,為大家展示ChatGPT在程式設計開發方面的無限潛力。有了ChatGPT的力量,可以簡化工作流程,減少錯誤,甚至改進代碼!從作為初學者學習知識,到為面試做準備,所有你需要的,基本都覆寫了。

一口氣最全解讀ChatGPT程式設計超能力,13個章50個執行個體,小白也能懂

不過也要注意,ChatGPT雖然是一個強大的工具,但是它不能替代我們的知識和技能! TA隻輸出,不管對錯,最終用還是不用,都需要使用者自己拿主意。在享受它提供便利的同時,也要時刻保持學習的狀态,充實自己的技能。

一、代碼生成

ChatGPT,可以生成各種Web開發任務的代碼,解放時間,讓你的效率倍增!它不僅能生成簡潔明了的HTML和CSS代碼,還能輕松生成JavaScript函數,甚至資料庫查詢語句,都能輕松搞定Web開發。

1.1 提示詞:

Generate a semantic and accessible HTML and (framework) CSS [UI component] consisting of [component parts]. The [component parts] should be [layout].

舉例:

Generate a semantic HTML and Tailwind CSS "Contact Support" form consisting of the user's name, email, issue type, and message. The form elements should be stacked vertically and placed inside a card.

生成結果

下面是一個使用語義化HTML和Tailwind CSS建構的“聯系支援”表單,包含使用者的姓名、電子郵件、問題類型和留言。表單元素垂直堆疊,放置在一個卡片中。

<div class="bg-white rounded-lg shadow-lg p-6">
  <h2 class="text-2xl font-bold mb-4">聯系支援</h2>
  <form>
    <div class="mb-4">
      <label class="block text-gray-700 font-bold mb-2" for="name">
        姓名
      </label>
      <input class="appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="name" type="text" placeholder="您的姓名">
    </div>
    <div class="mb-4">
      <label class="block text-gray-700 font-bold mb-2" for="email">
        電子郵件
      </label>
      <input class="appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="email" type="email" placeholder="您的電子郵件">
    </div>
    <div class="mb-4">
      <label class="block text-gray-700 font-bold mb-2" for="issue-type">
        問題類型
      </label>
      <select class="appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="issue-type">
        <option value="" disabled selected>請選擇問題類型</option>
        <option value="billing">賬單問題</option>
        <option value="technical">技術支援</option>
        <option value="general">正常問題</option>
      </select>
    </div>
    <div class="mb-4">
      <label class="block text-gray-700 font-bold mb-2" for="message">
        留言
      </label>
      <textarea class="appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="message" rows="5" placeholder="請在這裡輸入您的留言"></textarea>
    </div>
    <button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" type="button">
      送出
    </button>
  </form>
</div>           

在這個表單中,姓名和電子郵件是必填字段,是以可以在輸入框中使用required屬性。您還可以根據需要自定義CSS樣式。

1.2 提示詞:

Write a JavaScript function. It accepts [input] and returns [output].

舉例:

Write a JavaScript function. It accepts a full name as input and returns avatar letters.

生成結果

以下是接受全名為輸入并傳回頭像字母的JavaScript函數:

function getAvatarLetters(fullName) {
  // 分割全名為名字和姓氏
  const names = fullName.trim().split(" ");
  let avatar = "";

  // 周遊每個名字并将其第一個字元添加到頭像中
  for (let i = 0; i < names.length; i++) {
    avatar += names[i][0];
  }

  // 如果頭像長度大于2,則将其截斷為兩個字元
  if (avatar.length > 2) {
    avatar = avatar.substring(0, 2);
  }

  // 傳回頭像
  return avatar;
}           

該函數将首先将輸入的全名分割成名字和姓氏,然後周遊每個名字并将其第一個字元添加到頭像中。如果頭像的長度大于2,則将其截斷為兩個字元。最後,該函數傳回頭像。

例如,如果輸入的全名為“張三”,則該函數将傳回“張”,如果輸入的全名為“張三豐”,則該函數将傳回“張三”。

1.3 提示詞:

Write a/ an [framework] API for [functionality]. It should make use of [database].

舉例:

Write an Express.js API to fetch the current user's profile information. It should make use of MongoDB.

生成結果

以下是使用Express.js和MongoDB編寫的API示例,用于擷取目前使用者的個人資料資訊:

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const app = express();

// 連接配接到MongoDB資料庫
mongoose.connect('mongodb://localhost/myapp', { useNewUrlParser: true })
  .then(() => console.log('MongoDB連接配接成功'))
  .catch((err) => console.error('MongoDB連接配接失敗:', err));

// 建立使用者模型
const userSchema = new mongoose.Schema({
  name: String,
  email: String,
  password: String
});

const User = mongoose.model('User', userSchema);

// 添加中間件
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// 定義路由
app.get('/api/profile', (req, res) => {
  const userId = req.userId; // 假設已經通過身份驗證擷取到目前使用者的ID
  User.findById(userId, (err, user) => {
    if (err) {
      console.error('擷取使用者資訊失敗:', err);
      res.status(500).send('擷取使用者資訊失敗');
    } else if (!user) {
      res.status(404).send('找不到使用者資訊');
    } else {
      const userInfo = {
        name: user.name,
        email: user.email
      };
      res.send(userInfo);
    }
  });
});

// 啟動伺服器
const port = 3000;
app.listen(port, () => console.log(`伺服器已啟動,端口号:${port}`));           

這個API定義了一個/api/profile的GET路由,用于擷取目前使用者的個人資料資訊。在路由處理程式中,首先從請求對象中擷取目前使用者的ID,然後使用User.findById()方法從資料庫中查找該使用者的資訊。如果出現錯誤,會向用戶端發送500錯誤響應;如果找不到使用者,會發送404響應;否則,會将使用者的姓名和電子郵件資訊組成一個對象,發送給用戶端。

請注意,這個示例中的代碼假定已經實作了使用者身份驗證,并且可以從請求對象中擷取目前使用者的ID。如果您的應用程式沒有實作身份驗證功能,那麼您需要在路由處理程式中添加相應的代碼來實作身份驗證。

1.4 提示詞:

The database has [comma-separated table names]. Write a [database] query to fetch [requirement].

舉例:

The database has students and course tables. Write a PostgreSQL query to fetch a list of students who are enrolled in at least 3 courses.

生成結果

以下是一個 PostgreSQL 查詢,用于擷取至少選修了3門課程的學生名單:

SELECT students.name as 學生名單
FROM students
JOIN course ON students.id = course.student_id
GROUP BY students.id, students.name
HAVING COUNT(course.id) >= 3;           

該查詢使用了 JOIN 操作來将 students 表與 course 表關聯,并使用 GROUP BY 來按學生進行分組。然後使用 HAVING 子句來篩選至少選修了3門課程的學生,并将結果顯示為“學生名單”的列。

二、代碼補全

借助AI的力量,ChatGPT還可以建議與您的上下文和風格比對的代碼補全。

  • • 2.1提示詞:
Complete the code [code snippet]

舉例:

Complete the code:
const animals = ["dogs", "cats", "birds", "fish"];
let animal = animals[Math.floor(Math.random() * animals.length)];

switch (animal) {
  case "dogs":
    console.log(
      "Dogs are wonderful companions. They make us smile."
    );
    break;
}           
通常,以冒号結尾并将代碼塊粘貼到新行是一個最佳實踐。使用三個反引号 [code] 或三個雙引号 """[code]""" 來分隔代碼塊也是一個不錯的選擇。

生成結果

const animals = ["dogs", "cats", "birds", "fish"];
let animal = animals[Math.floor(Math.random() * animals.length)];

switch (animal) {
  case "dogs":
    console.log(
      "Dogs are wonderful companions. They make us smile."
    );
    break;
  case "cats":
    console.log(
      "Cats are independent and have a mind of their own."
    );
    break;
  case "birds":
    console.log(
      "Birds are fascinating creatures with beautiful feathers."
    );
    break;
  case "fish":
    console.log(
      "Fish come in many different colors and sizes, and can be kept as pets."
    );
    break;
  default:
    console.log("Sorry, I'm not familiar with that animal.");
}           

上述代碼定義了一個包含四種動物名稱的字元串數組 animals,然後使用 Math.random() 方法從 animals 數組中随機選擇一個元素,并将其指派給變量 animal。

接下來,代碼使用 switch 語句根據 animal 的值執行不同的操作。第一個 case 是針對 "dogs" 的,它向控制台輸出一條關于狗是美好夥伴的資訊。

為了完成這段代碼,我們可以添加更多的 case 語句來處理 animals 數組中的其他動物,并附上相應的關于每種動物的資訊。我們還可以添加一個 default 情況,如果 animal 變量與任何 case 值都不比對,則會記錄一條消息。

三、代碼轉換

作為一名開發人員,我們可能需要處理使用不同語言或架構編寫的代碼。通過ChatGPT,可以輕松地将代碼片段從一種語言或架構轉換為另一種。

  • • 3.1 提示詞:
Convert the below code snippet from [language/ framework] to [language/ framework]: [code snippet]

舉例:

Convert the below code snippet from JavaScript to TypeScript
function nonRepeatingWords(str1, str2) {
  const map = new Map();
  const res = [];
  // Concatenate the strings
  const str = str1 + " " + str2;
  // Count the occurrence of each word
  str.split(" ").forEach((word) => {
    map.has(word) ? map.set(word, map.get(word) + 1) : map.set(word, 1);
  });
  // Select words which occur only once
  for (let [key, val] of map) {
    if (val === 1) {
      res.push(key);
    }
  }
  return res;
}           

生成結果

以下是 TypeScript 代碼:

function nonRepeatingWords(str1: string, str2: string): string[] {
  const map = new Map<string, number>();
  const res: string[] = [];
  // Concatenate the strings
  const str = str1 + " " + str2;
  // Count the occurrence of each word
  str.split(" ").forEach((word) => {
    map.has(word) ? map.set(word, map.get(word)! + 1) : map.set(word, 1);
  });
  // Select words which occur only once
  for (let [key, val] of map) {
    if (val === 1) {
      res.push(key);
    }
  }
  return res;
}           

在 TypeScript 中,我們需要顯式地聲明每個參數和傳回值的類型。在這個例子中,str1 和 str2 的類型都是 string,傳回值的類型是 string[]。

另外,在 map.get(word) 中,我們需要使用非空斷言操作符 !,因為 map.get() 方法傳回的類型是 number | undefined,我們需要確定它不是 undefined 才能執行 +1 操作。

  • • 3.2 提示詞:Convert the below code using [CSS framework] to use [CSS framework]: [code snippet]
舉例: Convert the below code using Bootstrap to use Tailwind CSS: [code snippet]
<div class="container">                      
    <div class="row text-center justify-content-center mb-5">
        <div class="col-xl-6 col-lg-8">
            <h2 class="font-weight-bold">A Company Evolution</h2>
            <p class="text-muted">We’re very proud of the path we’ve taken. Explore the history that made us the company we are today.</p>
        </div>
    </div>

    <div class="row">
        <div class="col">
            <div class="timeline-steps aos-init aos-animate" data-aos="fade-up">
                <div class="timeline-step">
                    <div class="timeline-content" data-toggle="popover" data-trigger="hover" data-placement="top" title="" data-content="And here's some amazing content. It's very engaging. Right?" data-original-title="2003">
                        <div class="inner-circle"></div>
                        <p class="h6 mt-3 mb-1">2022</p>
                        <p class="h6 text-muted mb-0 mb-lg-0">Favland Founded</p>
                    </div>
                </div>
                <div class="timeline-step mb-0">
                    <div class="timeline-content" data-toggle="popover" data-trigger="hover" data-placement="top" title="" data-content="And here's some amazing content. It's very engaging. Right?" data-original-title="2020">
                        <div class="inner-circle"></div>
                        <p class="h6 mt-3 mb-1">2023</p>
                        <p class="h6 text-muted mb-0 mb-lg-0">In Fortune 500</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
           

生成結果

<div class="container">                      
    <div class="flex items-center justify-center mb-5">
        <div class="max-w-3xl">
            <h2 class="font-bold text-2xl md:text-3xl">A Company Evolution</h2>
            <p class="text-gray-600 mt-2">We’re very proud of the path we’ve taken. Explore the history that made us the company we are today.</p>
        </div>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div class="p-4">
            <div class="relative">
                <div class="absolute left-1/2 transform -translate-x-1/2 top-0 h-full w-1 bg-gray-300 pointer-events-none"></div>
                <div class="relative flex items-start space-x-3">
                    <div class="h-12 w-12 rounded-full bg-green-500 flex items-center justify-center">
                        <span class="text-white font-bold">2022</span>
                    </div>
                    <div class="flex-1 min-w-0">
                        <div class="text-gray-800 font-bold">Favland Founded</div>
                        <p class="text-gray-600 mt-1">And here's some amazing content. It's very engaging. Right?</p>
                    </div>
                </div>
            </div>
        </div>
        <div class="p-4">
            <div class="relative">
                <div class="absolute left-1/2 transform -translate-x-1/2 top-0 h-full w-1 bg-gray-300 pointer-events-none"></div>
                <div class="relative flex items-start space-x-3">
                    <div class="h-12 w-12 rounded-full bg-green-500 flex items-center justify-center">
                        <span class="text-white font-bold">2023</span>
                    </div>
                    <div class="flex-1 min-w-0">
                        <div class="text-gray-800 font-bold">In Fortune 500</div>
                        <p class="text-gray-600 mt-1">And here's some amazing content. It's very engaging. Right?</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>           

四、代碼解讀

ChatGPT可以幫助我們解讀代碼,通過提供有關代碼的解釋,回答特定問題來實作。在讀别人的代碼,或者嘗試了解複雜功能時,非常有用且高效。

  • • 4.1 提示詞:Explain the following [language] snippet of code: [code block]
  • • 4.2 提示詞:What does this code do: [accepted answer code from stack overflow]

舉例: What does this code do:

function checkNested(obj /*, level1, level2, ... levelN*/) {
  var args = Array.prototype.slice.call(arguments, 1);

  for (var i = 0; i < args.length; i++) {
    if (!obj || !obj.hasOwnProperty(args[i])) {
      return false;
    }
    obj = obj[args[i]];
  }
  return true;
}

var test = {level1:{level2:{level3:'level3'}} };

checkNested(test, 'level1', 'level2', 'level3'); // true
checkNested(test, 'level1', 'level2', 'foo'); // false           

生成結果

這段 JavaScript 代碼定義了一個名為 checkNested 的函數,用于檢查嵌套對象中是否存在指定的屬性路徑。

函數接受一個對象作為第一個參數,後面跟着一個或多個字元串參數,表示要檢查的屬性路徑。函數周遊這些屬性路徑,檢查對象是否具有每個路徑中指定的屬性,如果存在,則将對象更新為該屬性的值,繼續檢查下一個屬性路徑,如果不存在,則傳回 false。

如果函數成功檢查了所有的屬性路徑,則傳回 true。如果任何一個屬性路徑不存在,則傳回 false。

函數使用了 Array.prototype.slice.call 方法,将參數清單轉換為一個數組。它還使用了 hasOwnProperty 方法,以確定對象中隻檢查實際存在的屬性。

在代碼的最後,它定義了一個名為 test 的對象,該對象包含三個嵌套屬性。然後,它調用 checkNested 函數兩次,一次檢查屬性路徑 'level1.level2.level3' 是否存在,另一次檢查屬性路徑 'level1.level2.foo' 是否存在,并輸出結果。第一次調用傳回 true,因為該屬性路徑存在,第二次調用傳回 false,因為該屬性路徑不存在。

五、代碼評審

代碼審查是軟體開發的重要環節。我們自己的代碼,自己通常很難發現bug所在。可以借助ChatGPT, 讓TA來評審代碼,找出其中可能存在的bug,以便讓代碼更健壯。

  • • 5.1 提示詞:Review the following [language] code for code smells and suggest improvements: [code block]
  • • 5.2 提示詞:Identify any security vulnerabilities in the following code:
var unArray = ["yousif", "ali", "thaer", "michael", "ahmedwael", "ahmedmagdy", "abdo", "ahmedkhaled1", "ahmedkhaled2", "ahmedkhaled3", "ahmedkhaled4", "ahmedkhaled5"];
var pwArray = ["123", "123", "123", "123", "123", "123", "123", "123", "123", "123", "123", "123"];
for (var i = 0; i < unArray.length; i++) {
  if ((un == unArray[i]) && (pw == pwArray[i])) {
    valid = false;
    break;
  }
}           

生成結果

此代碼段的目的是驗證輸入的使用者名和密碼是否與預定義的使用者名和密碼比對。但是,此代碼段存在以下安全漏洞:

  1. 1. 寫死的使用者名和密碼:此代碼段将使用者名和密碼寫死到變量中,這意味着任何人都可以檢視源代碼并獲得這些憑據,進而導緻安全風險。
  2. 2. 明文密碼存儲:該代碼段将密碼存儲在明文格式中。這是一個嚴重的安全漏洞,因為攻擊者可以輕松地獲得這些密碼并通路使用者的帳戶。
  3. 3. 未經驗證的輸入:此代碼段未對輸入的使用者名和密碼進行任何驗證。這可能導緻攻擊者通過暴力攻擊等方式輕松地通路使用者帳戶。

是以,建議對代碼進行以下更改以提高其安全性:

  1. 1. 使用加密算法存儲密碼,例如SHA-256等。
  2. 2. 避免寫死憑據并将其存儲在外部存儲器中,例如資料庫。
  3. 3. 對輸入的使用者名和密碼進行驗證,例如檢查輸入是否包含惡意腳本,或是否為字元串等。

六、代碼重構

通常在寫代碼的時候,有一個 todo 想要重構這段代碼,可以總是太忙沒時間做。ChatGPT完全可以勝任,根據已存在的代碼,讓TA來改寫,效率會高很多。

  • • 6.1 提示詞:Refactor the given [language] code to improve its error handling and resilience: [code block]
  • • 6.2 提示詞:Refactor the given [language] code to make it more modular: [code block]
  • • 6.3 提示詞:Refactor the given [language] code to improve performance: [code block]
  • • 6.4 提示詞:Refactor the below component code to be responsive across mobile, tablet, and desktop screens: [code block]
  • • 6.5 提示詞:Suggest descriptive and meaningful names for variables and functions, making it easier to understand the purpose of each element in your code: [code snippet]
  • • 6.6 提示詞:Suggest ways to simplify complex conditionals and make them easier to read and understand: [code snippet]

七、找bug+修複bug

作為開發人員,我們知道找bug有多難,複現異常簡直不要太繁瑣。然而,借助ChatGPT提示,我們可以輕松識别和解決那些可能引起問題的煩人漏洞。

  • • 7.1 提示詞:Find any bugs in the following code: [code snippet]
  • • 7.2 提示詞:I am getting the error [error] from the following snippet of code: [code snippet]. How can I fix it?

八、系統設計與架構

ChatGPT能夠提供關于如何用不同技術堆棧設計系統的有價值見解和建議,甚至可以幫你比較不同技術堆棧的設計和架構哦!無論是在建構Web應用、移動應用還是分布式系統方面,ChatGPT都可以幫你設計出可擴充、可靠且易于維護的架構,滿足你的需求。

  • • 8.1 提示詞:You are an expert at system design and architecture. Tell me how to design a [system]. The technology stack is [comma-separated list of technologies].

舉例:

You are an expert at system design and architecture. Tell me how to design a hotel reservation system. The technology stack is Next.js and Firebase.

生成結果

酒店預訂系統的設計需要考慮以下幾個方面:

  1. 1. 需求分析:明确系統需要實作的功能,比如使用者注冊、酒店資訊管理、房間預訂、訂單管理、支付等等。
  2. 2. 資料庫設計:設計資料庫結構,包括酒店資訊、房間資訊、使用者資訊、訂單資訊等,以及各種關聯關系,比如房間和酒店之間的關聯、使用者和訂單之間的關聯等。
  3. 3. 後端開發:使用 Next.js 和 Firebase 開發後端 API,實作與資料庫的互動,處理使用者請求,傳回相應的資料。
  4. 4. 前端開發:使用 Next.js 和 Firebase 開發前端界面,實作使用者注冊、酒店資訊展示、房間預訂、訂單管理等功能。
  5. 5. 安全性設計:采用安全的開發方式和架構,對使用者資料進行加密和保護,確定系統安全可靠。
  6. 6. 性能優化:優化系統性能,保證系統響應速度和并發通路量。
  7. 7. 測試和部署:進行全面的測試,確定系統的穩定性和可用性,并将系統部署到生産環境中。

總的來說,設計一個酒店預訂系統需要綜合考慮多個方面,包括需求分析、資料庫設計、後端開發、前端開發、安全性設計、性能優化、測試和部署等。使用 Next.js 和 Firebase 技術棧可以提高開發效率和系統的可靠性,但仍需要細心謹慎地處理每一個環節。

  • • 8.2 提示詞:Contrast the design and architecture with [comma-separated list of technologies] as the technology stack.

舉例:

Contrast the design and architecture with React and Supabase as the technology stack.

生成結果

技術堆棧設計和架構特點React- 用于建構使用者界面的JavaScript庫

- 使用元件化的方式來建構應用程式

- 将UI分解為元件,然後在這些元件之間建構資料流

- 使得開發人員能夠更好地組織代碼,并減少應用程式中的重複代碼Supabase- 開源的後端即服務平台

- 提供了一系列工具和服務,使得開發人員能夠更輕松地建構和維護資料庫驅動的應用程式

- 使用PostgreSQL作為其資料庫引擎

- 提供了一系列API和工具,使得開發人員能夠更好地與資料庫互動

- 提供了實時資料推送和身份驗證等功能,使得開發人員能夠更好地建構實時應用程式和安全的使用者身份驗證系統

九、SEO優化

讓ChatGPT給我們的網站提提建議,從SEO優化的角度進行修改。

  • • 9.1 提示詞:How to improve SEO for a landing page?
  • • 9.2 提示詞:Give an example section of the HTML code that is optimized for Search Engine Optimization (SEO) for a [website]

舉例:

Give an example section of the HTML code that is optimized for Search Engine Optimization (SEO) for a social networking site for athletes

生成結果

以下是一個針對運動員社交網絡網站的頭部HTML代碼示例,優化了搜尋引擎優化(SEO):

<head>
  <title>運動員社交網絡 - 競技場</title>
  <meta name="description" content="競技場是一個專門為運動員和體育愛好者打造的社交網絡,您可以在此找到類似的人,分享您的運動成果和比賽經驗。">
  <meta name="keywords" content="運動員社交網絡, 運動員社交媒體, 體育社交網絡, 競技場">
  <meta name="author" content="競技場團隊">
  <link rel="canonical" href="athletesocialnetwork">
  <meta name="robots" content="index, follow">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>           

在這個頭部HTML代碼示例中,可以看到以下優化措施:

  • • <title> 标簽包含了網站的主要關鍵詞“運動員社交網絡”,并在結尾加上品牌名稱“競技場”。
  • • <meta name="description"> 标簽提供了網站的簡要描述,包含關鍵詞“運動員”、“體育”、“社交網絡”,有助于搜尋引擎了解網站内容。
  • • <meta name="keywords"> 标簽包含了網站的關鍵詞,包括“運動員社交網絡”、“運動員社交媒體”、“體育社交網絡”、“競技場”。
  • • <meta name="author"> 标簽提供了網站的作者資訊。
  • • <link rel="canonical"> 标簽指定了網站的主要URL,防止搜尋引擎将相似内容的多個URL視為不同的頁面。
  • • <meta name="robots"> 标簽訓示搜尋引擎索引和跟蹤網站内容。
  • • <meta name="viewport"> 标簽指定了網站在移動裝置上的展示方式。

這些優化措施有助于提高網站的搜尋引擎排名,吸引更多的運動員和體育愛好者來通路并使用該社交網絡。

十、模拟資料

無論是為了測試還是示範,使用真實、有代表性的資料都非常重要。ChatGPT可以快速生成各種領域,各種格式的模拟資料。

  • • 10.1 提示詞:Generate a sample [data format] of [number] [entity] for a [domain]

舉例:

Generate a sample JSON of 5 products for a clothing e-commerce site

生成結果

以下是一家服裝電商網站的5個産品的JSON示例:

{
  "products": [
    {
      "id": "001",
      "name": "女式針織衫",
      "description": "舒适柔軟的女式針織衫,适合秋季穿着。",
      "price": 199.99,
      "image_url": "images/product001.jpg"
    },
    {
      "id": "002",
      "name": "男式夾克",
      "description": "時尚休閑的男式夾克,适合春季穿着。",
      "price": 299.99,
      "image_url": "images/product002.jpg"
    },
    {
      "id": "003",
      "name": "女式連衣裙",
      "description": "優雅時尚的女式連衣裙,适合晚宴等場合穿着。",
      "price": 499.99,
      "image_url": "images/product003.jpg"
    },
    {
      "id": "004",
      "name": "男式長袖襯衫",
      "description": "高品質面料的男式長袖襯衫,适合商務場合穿着。",
      "price": 399.99,
      "image_url": "images/product004.jpg"
    },
    {
      "id": "005",
      "name": "女式牛仔褲",
      "description": "休閑舒适的女式牛仔褲,适合日常穿着。",
      "price": 249.99,
      "image_url": "images/product005.jpg"
    }
  ]
}           

其中,每個産品都包括以下資訊:

  • • id:産品的唯一辨別符。
  • • name:産品的名稱。
  • • description:産品的描述資訊。
  • • price:産品的價格。
  • • image_url:産品的圖檔連結。
  • • 10.2 提示詞:You can also enter prompts after every response for more fine-grained control
Give me a list of [number] fields for [entity] on an e-commerce site
Add an “id” field that will be unique to each [entity]. Replace [existing field] with [new field]
Generate a sample [data format] of [number] such [entity] with realistic values

十一、寫注釋、寫文檔

開發人員,又要寫代碼,又要寫文檔,真的是太困難了。這一點都不高效。寫文檔這些髒活、累活,交給ChatGPT來幹吧。代碼貼給TA,文檔打出來,豈不美哉。

  • • 11.1 提示詞:Write comments for the code below: [code snippet]
  • • 11.2 提示詞:Write JSDoc comments for the below JavaScript function: [code snippet]

舉例:

Write JSDoc comments for the below JavaScript function:
function deleteInactiveUser(inactiveUsers) {
  if (inactiveUsers.length > 0) {
    const userToDelete = inactiveUsers.pop();

    // Delete the inactive user.
    return admin.auth().deleteUser(userToDelete.uid).then(() => {
      return logger.log(
          "Deleted user account",
          userToDelete.uid,
          "because of inactivity",
      );
    }).catch((error) => {
      return logger.error(
          "Deletion of inactive user account",
          userToDelete.uid,
          "failed:",
          error,
      );
    });
  } else {
    return null;
  }
}           

生成結果

以下是 JavaScript 函數的 JSDoc 注釋(中文版):

/**
 * 從給定的使用者數組中删除最後一個不活躍使用者,傳回 Promise。
 *
 * @param {Array} inactiveUsers - 包含不活躍使用者對象的數組。
 * @returns {Promise|null} 如果删除成功,傳回一個 Promise;如果 inactiveUsers 數組為空,傳回 null。
 *
 * @throws {Error} 如果 admin.auth().deleteUser() 方法出錯,抛出異常。
 */
function deleteInactiveUser(inactiveUsers) {
  if (inactiveUsers.length > 0) {
    const userToDelete = inactiveUsers.pop();

    // 删除不活躍使用者。
    return admin.auth().deleteUser(userToDelete.uid).then(() => {
      return logger.log(
          "删除使用者賬戶",
          userToDelete.uid,
          "因為不活躍",
      );
    }).catch((error) => {
      return logger.error(
          "删除不活躍使用者賬戶",
          userToDelete.uid,
          "失敗:",
          error,
      );
    });
  } else {
    return null;
  }
}           

十二、寫指令

開發代碼,比如用git管理代碼倉庫,使用 npm 管理本地代碼的運作,編譯,測試等等。每次重寫,固然是乏味的。讓ChatGPT來幹吧。

  • • 12.1 提示詞:Write a shell command to [requirement]

舉例:

Write a shell command to delete all files with the extension '.log' in the 'logs' folder

生成結果

以下是删除“logs”檔案夾中所有擴充名為“.log”的檔案的shell指令:

rm logs/*.log           

該指令使用了“rm”指令來删除檔案,以及通配符“”來比對檔案名。通配符“”表示比對任何字元序列,是以指令将删除所有擴充名為“.log”的檔案,無論它們的名稱如何。請注意,這将不會删除子目錄中的任何檔案。

  • • 12.2 提示詞:Write a git command to [requirement]

舉例:

Write a git command to undo the previous commit

生成結果

使用Git指令撤銷之前的送出,可以使用以下指令:

git reset HEAD~1           

這将取消上一次送出并将所有更改放回工作目錄。如果您希望保留更改并将其保留在暫存區中,則可以使用以下指令:

git reset --soft HEAD~1           

這将取消上一次送出并将更改保留在暫存區中,以便您可以重新送出它們。請注意,這些指令将更改曆史記錄,是以如果您在共享存儲庫上工作,則需要小心使用它們。

  • • 12.3 提示詞:Explain the following command [command]

舉例:

Explain the following command [git switch -c feat/qwik-loaders]

生成結果

這條指令的作用是建立并切換到一個名為 "feat/qwik-loaders" 的新分支。具體解釋如下:

  • • "git switch" 是一個 Git 指令,用于切換分支或恢複工作樹檔案。在這個指令中,它用于建立并切換到一個新的分支。
  • • "-c" 參數用于建立新分支。如果該參數沒有被指定,"git switch" 指令将隻切換到已存在的分支。
  • • "feat/qwik-loaders" 是新分支的名稱。這個名稱應該能夠清晰地表達新分支所涉及的特性或功能。在這個例子中,這個新分支可能是為了實作某個名為 "qwik loaders" 的功能。

是以,這個指令的作用是在目前分支基礎上建立一個名為 "feat/qwik-loaders" 的新分支,并切換到該分支。

十三、寫正規表達式

正規表達式實乃天書,非人類所能及。讓ChatGPT上吧。

  • • 13.1 提示詞:Explain this regular expression: [regex]

舉例:

Explain this regular expression in JavaScript: const regex = /^[A-Za-z0–9._%+-]+@[A-Za-z0–9.-]+\.[A-Za-z]{2,}$/;

生成結果

這個正規表達式可以用于比對電子郵件位址。它的 JavaScript 表示為:

const regex = /^[A-Za-z0–9._%+-]+@[A-Za-z0–9.-]+\\.[A-Za-z]{2,}$/;           

這個正規表達式可以解讀為:

  • • ^: 比對輸入的開始
  • • [A-Za-z0–9._%+-]+: 比對一個或多個大寫或小寫字母、數字、點(.)、下劃線(_)、百分号(%)、加号(+)、減号(-)
  • • @: 比對 @ 符号
  • • [A-Za-z0–9.-]+: 比對一個或多個大寫或小寫字母、數字、點(.)、減号(-)
  • • \\.: 比對點(.),由于點在正規表達式中有特殊意義,是以需要使用反斜杠轉義
  • • [A-Za-z]{2,}: 比對兩個或更多大寫或小寫字母
  • • $: 比對輸入的結尾

是以,這個正規表達式可以比對所有符合标準格式的電子郵件位址,例如 [email protected][email protected]

  • • 13.2 提示詞:Your role is to generate regular expressions that match specific patterns in text. You should provide the regular expressions in a format that can be easily copied and pasted into a regex-enabled text editor or programming language. Generate a regular expression that matches [text].

寫在最後

如果是Web開發攻城獅,那就必須要使用ChatGPT,快速優化我們的工作流程,提高效率,讓編碼任務變得更加簡單易行。

當然啦,ChatGPT雖然是一個強大的工具,但要記住它也有自己的局限性,隻能作為知識和技能的補充哦。

在不斷研究的同時,可以更好地發揮AI在Web開發中的優勢。利用ChatGPT這樣有價值的資源,大家可以自信地航行在Web開發的海洋中,提高自己的技能水準哦!