首頁  >  文章  >  web前端  >  JavaScript 基礎知識:第 5 部分

JavaScript 基礎知識:第 5 部分

Barbara Streisand
Barbara Streisand原創
2024-10-18 20:41:03372瀏覽

JavaScript Essentials: Part 5

之前在《JavaScript 基礎知識:第 4 部分》中,我們討論了 if 和 else 語句、for 和 while 迴圈。在這一部分,我們將看看:

  • 功能
  • 回調、承諾、非同步與等待
  • 下一件大事

評論

評論很棒,我們現在要討論它。這麼晚了,你應該知道什麼是評論了。不管怎樣,我們程式中的一條註解並沒有被執行。註釋旨在記錄我們的程式碼。在 Javascript 中加入註解的方法有3種。我們有內聯、多行和 JsDoc。

線上

// this is a number
const numberOfBirds = 3;

// the above comment is useless since the initial value assigned to the variable
// is physically a number and the variable name also has a number in it
// so use comments wisely by using proper naming

多行

/* 
Everything in here is or will be ignored.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.


*/

const emptyString = "";

JsDoc

/**
 * This is a multiline comment
 *
 * But used for documentation
 */

評論可以放在任何地方;但是,將它們放置在一行程式碼之後(或末尾)或者其下方或上方時請小心。

分號

在 javascript 中,分號 ; 不是必需的,但有時它會有所幫助。有一些工具可以幫助您。分號表示語句的結束。很好。

縮排

縮排用於排列程式碼以使其清晰且易於閱讀。 Tab 鍵(鍵盤上)用於縮排。縮排有時是“製表符”或“空格”。空間一般是2或4個,如果你使用的是vscode,就不用擔心。

範例

JavaScript Essentials:第 4 部分中有一些練習,包括但不限於「fizzbuzz」、密碼和電子郵件驗證等。如果您遵循我的偽代碼,您會遇到一些問題。我將提供考慮順序的片段。

單一數字的嘶嘶聲

const givenNumber = 3;

if (givenNumber % 3 === 0 && givenNumber % 5 === 0) {
  console.log("fizzbuzz");
} else if (givenNumber % 3 === 0) {
  console.log("fizz");
} else if (givenNumber % 5 === 0) {
  console.log("buzz");
}

陣列的嘶嘶聲

const numbers = [3, 6, 10, 15];

for (const givenNumber of numbers) {
  if (givenNumber % 3 === 0 && givenNumber % 5 === 0) {
    console.log("fizzbuzz");
  } else if (givenNumber % 3 === 0) {
    console.log("fizz");
  } else if (givenNumber % 5 === 0) {
    console.log("buzz");
  }
}

密碼驗證

const veryWeakPassword = "PrQ1V_";
// const veryWeakPassword = "rtfy67Fg";
// const veryWeakPassword = "OlJgRc__1qwPVa";
console.log(`Password validation for "${veryWeakPassword}"`);

// - be six characters
if (veryWeakPassword.length !== 6) {
  console.log(
    `- Password must have 6 characters => "${veryWeakPassword}" has '${veryWeakPassword.length}' characters`
  );
}
// - start with uppercase p, 'P'
else if (!veryWeakPassword.startsWith("P")) {
  console.log(
    `- Password must start with 'P' => it is ${veryWeakPassword.startsWith(
      "P"
    )} that "${veryWeakPassword}" starts with 'P'`
  );
}
// - end with underscore
else if (!veryWeakPassword.endsWith("_")) {
  console.log(
    `- Password must end with '_' => it is ${veryWeakPassword.endsWith(
      "_"
    )} that "${veryWeakPassword}" ends with '_'`
  );
}
// - have uppercase q, 'Q'
else if (!veryWeakPassword.includes("Q")) {
  console.log(
    `- Password must have uppercase q, 'Q' => it is ${veryWeakPassword.includes(
      "Q"
    )} that "${veryWeakPassword}" has 'Q'`
  );
}
// - have lowercase r, 'r'
else if (!veryWeakPassword.includes("r")) {
  console.log(
    `- Password must have lowercase r, 'r' => it is ${veryWeakPassword.includes(
      "r"
    )} that "${veryWeakPassword}" has 'r'`
  );
}
// - have its fifth character as uppercase v, 'V'
// fifth character with have index = fifth position - 1 = 4
// const fifthCharacter = veryWeakPassword[4]
else if (veryWeakPassword.charAt(4) !== "V") {
  console.log(
    `- Password must have its fifth character as uppercase v, 'V' => "${veryWeakPassword}" has its 5th character as '${veryWeakPassword.charAt(
      4
    )}'`
  );
} else {
  console.log(`${veryWeakPassword} is a valid password`);
}

其他一些解決方案將使用嵌套的 if 和 else。

// password validation
const veryWeakPassword = "PrQ1V_";
// const veryWeakPassword = "rtfy67Fg";
// const veryWeakPassword = "OlJgRc__1qwPVa";
console.log(`Password validation for "${veryWeakPassword}"`);

// - be six characters
if (veryWeakPassword.length === 6) {
  if (veryWeakPassword.startsWith("P")) {
    if (veryWeakPassword.endsWith("_")) {
      if (veryWeakPassword.includes("Q")) {
        if (veryWeakPassword.includes("r")) {
          if (veryWeakPassword.charAt(4) === "V") {
            console.log(`${veryWeakPassword} is a valid password`);
          } else {
            console.log(
              `- Password must have its fifth character as uppercase v, 'V' => "${veryWeakPassword}" has its 5th character as '${veryWeakPassword.charAt(
                4
              )}'`
            );
          }
        } else {
          console.log(
            `- Password must have lowercase r, 'r' => it is ${veryWeakPassword.includes(
              "r"
            )} that "${veryWeakPassword}" has 'r'`
          );
        }
      } else {
        console.log(
          `- Password must have uppercase q, 'Q' => it is ${veryWeakPassword.includes(
            "Q"
          )} that "${veryWeakPassword}" has 'Q'`
        );
      }
    } else {
      console.log(
        `- Password must end with '_' => it is ${veryWeakPassword.endsWith(
          "_"
        )} that "${veryWeakPassword}" ends with '_'`
      );
    }
  } else {
    console.log(
      `- Password must start with 'P' => it is ${veryWeakPassword.startsWith(
        "P"
      )} that "${veryWeakPassword}" starts with 'P'`
    );
  }
} else {
  console.log(
    `- Password must have 6 characters => "${veryWeakPassword}" has '${veryWeakPassword.length}' characters`
  );
}

你對這兩個片段有何看法?實際上,第二個片段雖然有效,但並不是那麼好。

功能

函數是一段可以重複使用的程式碼。通常,函數執行特定的操作。一件事。它可以是任何東西。

讓我們看看 JavaScript 中函數的一般形式(結構)。

// this is a number
const numberOfBirds = 3;

// the above comment is useless since the initial value assigned to the variable
// is physically a number and the variable name also has a number in it
// so use comments wisely by using proper naming
  • function 是建立函數時所需的關鍵字。當你想使用for迴圈時,需要使用for關鍵字。
  • functionName 應該是函數的名稱。命名變數的想法適用於函數。
  • /* 參數 */ 指的是你要傳遞給函數的資料。
  • // do some 是我們希望執行的操作或計算。函數通常在完成一些處理後傳回資料。有時卻並非如此。它只是更新了一些數據就完成了。
  • { // do some } 是函數體或區塊

我們可以有一個印出「hello world」的函數

/* 
Everything in here is or will be ignored.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.


*/

const emptyString = "";

我們幫自己一個忙,用一個描述函數功能的名稱來命名我們的函數。

現在,當我們有一個函數時,我們必須「呼叫」它才能執行它。要呼叫函數,您需要在函數名稱後面跟著 ( 和 )。如果函數採用 參數 ,您將在 ( 和 ) 中傳遞 參數 。在我們的例子中,對於「hello world」函數,我們必須執行 printHelloWorld();.

/**
 * This is a multiline comment
 *
 * But used for documentation
 */

讓我們朝著一個小方向前進,這將擴大我們的武器庫並使創建函數變得有趣。考慮這個函數,它將兩個數字相加,然後列印一條文字告訴您發生了什麼。

const givenNumber = 3;

if (givenNumber % 3 === 0 && givenNumber % 5 === 0) {
  console.log("fizzbuzz");
} else if (givenNumber % 3 === 0) {
  console.log("fizz");
} else if (givenNumber % 5 === 0) {
  console.log("buzz");
}

這能給你一些想法嗎?我們可以使用函數來編寫“fizzbuzz”和驗證。我們可以如此小氣和精緻,以至於我們將每個驗證需求寫成一個函數。它發生了。只是不要做得太過分。

現在,考慮 add 函數。如果我們想添加不同的數字,我們該怎麼辦?我們可以建立另一個函數。我們也可以直接改變這些值。正確的?是的。您會對我們用函數實現的功能感到驚訝。

首先,如果我們想增加不同的數字,我們可以更改數字。

const numbers = [3, 6, 10, 15];

for (const givenNumber of numbers) {
  if (givenNumber % 3 === 0 && givenNumber % 5 === 0) {
    console.log("fizzbuzz");
  } else if (givenNumber % 3 === 0) {
    console.log("fizz");
  } else if (givenNumber % 5 === 0) {
    console.log("buzz");
  }
}

好吧,讓我們將函數改為 6 和 100 相加。現在我們必須改變這個功能。對此有一個解決方案,那就是引入參數(透過變數取得資料)。然後我們將這些數據作為參數傳遞。

讓我們來分析一下我們的 add 函數。 add 函數對 x 和 y 以及運算元進行運算。我們可以透過將 x 和 y 作為參數傳遞給 x 和 y 不同的值。

const veryWeakPassword = "PrQ1V_";
// const veryWeakPassword = "rtfy67Fg";
// const veryWeakPassword = "OlJgRc__1qwPVa";
console.log(`Password validation for "${veryWeakPassword}"`);

// - be six characters
if (veryWeakPassword.length !== 6) {
  console.log(
    `- Password must have 6 characters => "${veryWeakPassword}" has '${veryWeakPassword.length}' characters`
  );
}
// - start with uppercase p, 'P'
else if (!veryWeakPassword.startsWith("P")) {
  console.log(
    `- Password must start with 'P' => it is ${veryWeakPassword.startsWith(
      "P"
    )} that "${veryWeakPassword}" starts with 'P'`
  );
}
// - end with underscore
else if (!veryWeakPassword.endsWith("_")) {
  console.log(
    `- Password must end with '_' => it is ${veryWeakPassword.endsWith(
      "_"
    )} that "${veryWeakPassword}" ends with '_'`
  );
}
// - have uppercase q, 'Q'
else if (!veryWeakPassword.includes("Q")) {
  console.log(
    `- Password must have uppercase q, 'Q' => it is ${veryWeakPassword.includes(
      "Q"
    )} that "${veryWeakPassword}" has 'Q'`
  );
}
// - have lowercase r, 'r'
else if (!veryWeakPassword.includes("r")) {
  console.log(
    `- Password must have lowercase r, 'r' => it is ${veryWeakPassword.includes(
      "r"
    )} that "${veryWeakPassword}" has 'r'`
  );
}
// - have its fifth character as uppercase v, 'V'
// fifth character with have index = fifth position - 1 = 4
// const fifthCharacter = veryWeakPassword[4]
else if (veryWeakPassword.charAt(4) !== "V") {
  console.log(
    `- Password must have its fifth character as uppercase v, 'V' => "${veryWeakPassword}" has its 5th character as '${veryWeakPassword.charAt(
      4
    )}'`
  );
} else {
  console.log(`${veryWeakPassword} is a valid password`);
}

我們沒有將 x 和 y 的值作為 add 中的內部值,而是傳遞它們。現在參數和實參之間的區別在於參數是在創建(定義)函數時傳遞的。參數是呼叫函數時傳遞的值。所以在函數add(x, y)中,x和y是參數(我們可以說佔位符,代表要傳遞給函數的資料)。在 add(3, 30); 中,3 和 30 作為參數傳遞(要處理的實際值)。請注意,參數和參數的順序必須匹配,否則我們將陷入嚴重的債務。

你覺得足以挑戰大佬們了嗎?嗯,我想你可以。你只需要保持冷靜並知道自己在做什麼。我將提供一些片段。

// this is a number
const numberOfBirds = 3;

// the above comment is useless since the initial value assigned to the variable
// is physically a number and the variable name also has a number in it
// so use comments wisely by using proper naming

對「嘶嘶聲」做同樣的事情。在程式碼片段周圍包裹一個函數。您不必對所使用的變數進行註解。看看需要將哪些資料傳遞給函數(輸入)。

我們可以傳遞任意多個參數給函數。但是,我鼓勵您設定一些限制。有一些專業人士說三個就夠了。有人說少於五個。你必須對此保持聰明才智。現在,假設只要參數數量超過三個,我們就會使用陣列或物件。是的。我們可以傳遞一個陣列或一個物件作為參數。

/* 
Everything in here is or will be ignored.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.


*/

const emptyString = "";

透過完成這個函數來寫一個計算數字數組平均值的函數。

/**
 * This is a multiline comment
 *
 * But used for documentation
 */

此時,應該清楚函數可以接受參數。實際上,我們的函數在計算完成後將傳回一個值或某個值。計算值從函數傳回。傳回值的函數的形式如下:

const givenNumber = 3;

if (givenNumber % 3 === 0 && givenNumber % 5 === 0) {
  console.log("fizzbuzz");
} else if (givenNumber % 3 === 0) {
  console.log("fizz");
} else if (givenNumber % 5 === 0) {
  console.log("buzz");
}
  • // return someValue 是這裡唯一的新東西。 return 是一個關鍵字。
  • someValue 是從函數傳回的值。它可以是任何東西,也可以是空的,一個空函數。別出汗。我們將修改一些我們之前寫的函數,這樣事情會更簡單。

還記得新增功能嗎?我們不會將值記錄在函數內,而是傳回它並將該值指派給變量,然後稍後重複使用該值。

const numbers = [3, 6, 10, 15];

for (const givenNumber of numbers) {
  if (givenNumber % 3 === 0 && givenNumber % 5 === 0) {
    console.log("fizzbuzz");
  } else if (givenNumber % 3 === 0) {
    console.log("fizz");
  } else if (givenNumber % 5 === 0) {
    console.log("buzz");
  }
}

這就像我們所說的一樣簡單。對calculateInterest函數做同樣的事情。

函數可以傳回任何可傳回的內容。

箭頭功能

箭頭函數是編寫函數的另一種方式。通常,當我有一個簡單的函數來執行非常小的“事情”或在數組或字串方法中進行循環時,我會使用箭頭函數。您可以使用它來代替函數聲明(命名函數)。我們說“函數”,表示我們要建立一個函數。箭頭函數與宣告式函數具有相同的功能。

箭頭函數之所以稱為箭頭函數,是因為 =>(胖箭頭運算子)。它的形式可能是您以前見過的:

const veryWeakPassword = "PrQ1V_";
// const veryWeakPassword = "rtfy67Fg";
// const veryWeakPassword = "OlJgRc__1qwPVa";
console.log(`Password validation for "${veryWeakPassword}"`);

// - be six characters
if (veryWeakPassword.length !== 6) {
  console.log(
    `- Password must have 6 characters => "${veryWeakPassword}" has '${veryWeakPassword.length}' characters`
  );
}
// - start with uppercase p, 'P'
else if (!veryWeakPassword.startsWith("P")) {
  console.log(
    `- Password must start with 'P' => it is ${veryWeakPassword.startsWith(
      "P"
    )} that "${veryWeakPassword}" starts with 'P'`
  );
}
// - end with underscore
else if (!veryWeakPassword.endsWith("_")) {
  console.log(
    `- Password must end with '_' => it is ${veryWeakPassword.endsWith(
      "_"
    )} that "${veryWeakPassword}" ends with '_'`
  );
}
// - have uppercase q, 'Q'
else if (!veryWeakPassword.includes("Q")) {
  console.log(
    `- Password must have uppercase q, 'Q' => it is ${veryWeakPassword.includes(
      "Q"
    )} that "${veryWeakPassword}" has 'Q'`
  );
}
// - have lowercase r, 'r'
else if (!veryWeakPassword.includes("r")) {
  console.log(
    `- Password must have lowercase r, 'r' => it is ${veryWeakPassword.includes(
      "r"
    )} that "${veryWeakPassword}" has 'r'`
  );
}
// - have its fifth character as uppercase v, 'V'
// fifth character with have index = fifth position - 1 = 4
// const fifthCharacter = veryWeakPassword[4]
else if (veryWeakPassword.charAt(4) !== "V") {
  console.log(
    `- Password must have its fifth character as uppercase v, 'V' => "${veryWeakPassword}" has its 5th character as '${veryWeakPassword.charAt(
      4
    )}'`
  );
} else {
  console.log(`${veryWeakPassword} is a valid password`);
}


// password validation
const veryWeakPassword = "PrQ1V_";
// const veryWeakPassword = "rtfy67Fg";
// const veryWeakPassword = "OlJgRc__1qwPVa";
console.log(`Password validation for "${veryWeakPassword}"`);

// - be six characters
if (veryWeakPassword.length === 6) {
  if (veryWeakPassword.startsWith("P")) {
    if (veryWeakPassword.endsWith("_")) {
      if (veryWeakPassword.includes("Q")) {
        if (veryWeakPassword.includes("r")) {
          if (veryWeakPassword.charAt(4) === "V") {
            console.log(`${veryWeakPassword} is a valid password`);
          } else {
            console.log(
              `- Password must have its fifth character as uppercase v, 'V' => "${veryWeakPassword}" has its 5th character as '${veryWeakPassword.charAt(
                4
              )}'`
            );
          }
        } else {
          console.log(
            `- Password must have lowercase r, 'r' => it is ${veryWeakPassword.includes(
              "r"
            )} that "${veryWeakPassword}" has 'r'`
          );
        }
      } else {
        console.log(
          `- Password must have uppercase q, 'Q' => it is ${veryWeakPassword.includes(
            "Q"
          )} that "${veryWeakPassword}" has 'Q'`
        );
      }
    } else {
      console.log(
        `- Password must end with '_' => it is ${veryWeakPassword.endsWith(
          "_"
        )} that "${veryWeakPassword}" ends with '_'`
      );
    }
  } else {
    console.log(
      `- Password must start with 'P' => it is ${veryWeakPassword.startsWith(
        "P"
      )} that "${veryWeakPassword}" starts with 'P'`
    );
  }
} else {
  console.log(
    `- Password must have 6 characters => "${veryWeakPassword}" has '${veryWeakPassword.length}' characters`
  );
}

讓我們用箭頭函數來重寫add函數。

function functionName(/* parameters */) {
  // do something
}

=>,表示從 x y 表達式傳回值。所以隱式使用了 return 關鍵字。同樣,我們可以使用 return 關鍵字從函數明確傳回一個值,但是,我們必須新增函數區塊。

// this is a number
const numberOfBirds = 3;

// the above comment is useless since the initial value assigned to the variable
// is physically a number and the variable name also has a number in it
// so use comments wisely by using proper naming

兩者之間的差異在於,在第二個中,我們新增了一個區塊 { 和 } 以及一個從函數傳回值的 return 關鍵字。同樣,您可以選擇是否傳回值。

將函數作為參數傳遞

我們可以將函數當作參數傳遞給其他函數。本質上,我們將函數視為值。讓我們考慮這個簡單的例子。

/* 
Everything in here is or will be ignored.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.


*/

const emptyString = "";

我們可以做到這一點的另一個地方是使用陣列方法或字串方法。考慮這個函數

/**
 * This is a multiline comment
 *
 * But used for documentation
 */

我們可以看到可以拉出回呼函數,(total, element) =>總元素,0。其實就是我們可以替換的總元素。

const givenNumber = 3;

if (givenNumber % 3 === 0 && givenNumber % 5 === 0) {
  console.log("fizzbuzz");
} else if (givenNumber % 3 === 0) {
  console.log("fizz");
} else if (givenNumber % 5 === 0) {
  console.log("buzz");
}

你知道我們傳遞了另一個函數,它接受 2 個數字參數並傳回一個數字。我們甚至不需要建立一個函數。

我們之前已經做過一些數學運算,但這次我們將使用函數來抽象運算子。

const numbers = [3, 6, 10, 15];

for (const givenNumber of numbers) {
  if (givenNumber % 3 === 0 && givenNumber % 5 === 0) {
    console.log("fizzbuzz");
  } else if (givenNumber % 3 === 0) {
    console.log("fizz");
  } else if (givenNumber % 5 === 0) {
    console.log("buzz");
  }
}

最後一個參數稱為預設參數,通常放置為
最後一個論點。這是你必須要做的事
使用預設值。這個片段與之前的沒有什麼不同
一個除了引入預設參數,這意味著第三個
參數,我們可以選擇是否為其傳遞值。

const veryWeakPassword = "PrQ1V_";
// const veryWeakPassword = "rtfy67Fg";
// const veryWeakPassword = "OlJgRc__1qwPVa";
console.log(`Password validation for "${veryWeakPassword}"`);

// - be six characters
if (veryWeakPassword.length !== 6) {
  console.log(
    `- Password must have 6 characters => "${veryWeakPassword}" has '${veryWeakPassword.length}' characters`
  );
}
// - start with uppercase p, 'P'
else if (!veryWeakPassword.startsWith("P")) {
  console.log(
    `- Password must start with 'P' => it is ${veryWeakPassword.startsWith(
      "P"
    )} that "${veryWeakPassword}" starts with 'P'`
  );
}
// - end with underscore
else if (!veryWeakPassword.endsWith("_")) {
  console.log(
    `- Password must end with '_' => it is ${veryWeakPassword.endsWith(
      "_"
    )} that "${veryWeakPassword}" ends with '_'`
  );
}
// - have uppercase q, 'Q'
else if (!veryWeakPassword.includes("Q")) {
  console.log(
    `- Password must have uppercase q, 'Q' => it is ${veryWeakPassword.includes(
      "Q"
    )} that "${veryWeakPassword}" has 'Q'`
  );
}
// - have lowercase r, 'r'
else if (!veryWeakPassword.includes("r")) {
  console.log(
    `- Password must have lowercase r, 'r' => it is ${veryWeakPassword.includes(
      "r"
    )} that "${veryWeakPassword}" has 'r'`
  );
}
// - have its fifth character as uppercase v, 'V'
// fifth character with have index = fifth position - 1 = 4
// const fifthCharacter = veryWeakPassword[4]
else if (veryWeakPassword.charAt(4) !== "V") {
  console.log(
    `- Password must have its fifth character as uppercase v, 'V' => "${veryWeakPassword}" has its 5th character as '${veryWeakPassword.charAt(
      4
    )}'`
  );
} else {
  console.log(`${veryWeakPassword} is a valid password`);
}

在 const Total = PerformActionOnArray(numArray, add); 我們可以直接傳遞一個函數

// password validation
const veryWeakPassword = "PrQ1V_";
// const veryWeakPassword = "rtfy67Fg";
// const veryWeakPassword = "OlJgRc__1qwPVa";
console.log(`Password validation for "${veryWeakPassword}"`);

// - be six characters
if (veryWeakPassword.length === 6) {
  if (veryWeakPassword.startsWith("P")) {
    if (veryWeakPassword.endsWith("_")) {
      if (veryWeakPassword.includes("Q")) {
        if (veryWeakPassword.includes("r")) {
          if (veryWeakPassword.charAt(4) === "V") {
            console.log(`${veryWeakPassword} is a valid password`);
          } else {
            console.log(
              `- Password must have its fifth character as uppercase v, 'V' => "${veryWeakPassword}" has its 5th character as '${veryWeakPassword.charAt(
                4
              )}'`
            );
          }
        } else {
          console.log(
            `- Password must have lowercase r, 'r' => it is ${veryWeakPassword.includes(
              "r"
            )} that "${veryWeakPassword}" has 'r'`
          );
        }
      } else {
        console.log(
          `- Password must have uppercase q, 'Q' => it is ${veryWeakPassword.includes(
            "Q"
          )} that "${veryWeakPassword}" has 'Q'`
        );
      }
    } else {
      console.log(
        `- Password must end with '_' => it is ${veryWeakPassword.endsWith(
          "_"
        )} that "${veryWeakPassword}" ends with '_'`
      );
    }
  } else {
    console.log(
      `- Password must start with 'P' => it is ${veryWeakPassword.startsWith(
        "P"
      )} that "${veryWeakPassword}" starts with 'P'`
    );
  }
} else {
  console.log(
    `- Password must have 6 characters => "${veryWeakPassword}" has '${veryWeakPassword.length}' characters`
  );
}

承諾

在任何事情之前,讓我們先定義一些術語。在我們的利基市場中,承諾很重要。

同步操作:這些操作是從上到下、一個接一個地順序執行的。對於某些操作A1A2A1必須在A2執行之前完成。這樣,A2 直到 A1 才會被執行。一次執行一個操作。這個缺點稱為阻塞。

function functionName(/* parameters */) {
  // do something
}

上面的輸出依照上面寫的線性順序。

// function to print "hello world"
function printHelloWorld() {
  console.log("Hello world");
}

簡而言之,到目前為止我們寫的程式碼都是以同步順序執行的,我們可以知道何時執行一行。

非同步操作:這些是不按順序執行的操作。這些操作同時運作。實際上,這些操作可能是同時運作的,一點一點。由於一個操作的成功或執行與順序無關,並且不會妨礙其他行的執行,因此我們將這種行為稱為非阻塞。我們無法判斷異步行何時被執行。

printHelloWorld();

// the output of this function will be on the console/terminal

這就是輸出。

function add() {
  const x = 3;
  const y = 20;

  const sum = x + y;

  console.log(`${x} + ${y} = ${sum}`);
}

add(); // 3 + 20 = 23

你能根據輸出辨識非同步操作嗎?

就是setTimeout函數。假設它在背景運行。它是非阻塞的,所以最後的console.log被執行了。

一些非同步操作

  • 網路請求(例如:API 呼叫)
  • 資料庫查詢
  • 檔案 I/O 操作
  • Javascript Web API(setTimeout、setInterval、fetch 等)

Promise 提供了一種管理或處理非同步操作的方法。它是一種了解非同步操作所處狀態、執行時間以及是否「完成」或失敗的方法。

讓我們創造一個承諾

承諾的形式為:

// this is a number
const numberOfBirds = 3;

// the above comment is useless since the initial value assigned to the variable
// is physically a number and the variable name also has a number in it
// so use comments wisely by using proper naming

new 和 Promise 是關鍵字。 solve 和reject 是回呼函數。我們可以用其他名稱替換它們。透過轉換,我們使用resolve和reject。

兌現承諾

Promise 有 then 方法,它提供解析值,catch 方法,它提供被拒絕的錯誤,還有finally,它是整個過程後清理的方法。最後是可選的。這是一個您可以玩玩的簡單範例。

/* 
Everything in here is or will be ignored.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.


*/

const emptyString = "";

查看輸出並了解程式碼是如何執行的。 console.log("再見");並不是最後一個被處死的。我們使用 Promise 建立非同步操作,並使用 then 和 catch 處理它。如果我們考慮按順序執行這些操作,那麼我們可以或必須將剩餘的邏輯放入 then 區塊中。

/**
 * This is a multiline comment
 *
 * But used for documentation
 */

發生了什麼事?

這種處理 Promise 的方法的問題在於,我們傾向於嵌套或連結此操作,然後塊會變胖,而且不那麼友好。那麼讓我們來看看 async 和 wait。

非同步和等待

在正常的資料流中,我們不希望非同步操作在背景運作。我們想聽它並使用它的結果做其他事情(就像我們在 then 和 catch 中所做的那樣)。

讓我們建立一個非同步操作並使用 async 和 wait 來處理它。

我們知道如何建立命名函數和箭頭函數。

const givenNumber = 3;

if (givenNumber % 3 === 0 && givenNumber % 5 === 0) {
  console.log("fizzbuzz");
} else if (givenNumber % 3 === 0) {
  console.log("fizz");
} else if (givenNumber % 5 === 0) {
  console.log("buzz");
}

要讓函數異步,我們使用 async 關鍵字。

const numbers = [3, 6, 10, 15];

for (const givenNumber of numbers) {
  if (givenNumber % 3 === 0 && givenNumber % 5 === 0) {
    console.log("fizzbuzz");
  } else if (givenNumber % 3 === 0) {
    console.log("fizz");
  } else if (givenNumber % 5 === 0) {
    console.log("buzz");
  }
}

現在無論什麼操作進入函數區塊,假設在我們想要建立的非同步函數中,我們都必須處理另一個非同步操作,然後我們可以使用await。

const veryWeakPassword = "PrQ1V_";
// const veryWeakPassword = "rtfy67Fg";
// const veryWeakPassword = "OlJgRc__1qwPVa";
console.log(`Password validation for "${veryWeakPassword}"`);

// - be six characters
if (veryWeakPassword.length !== 6) {
  console.log(
    `- Password must have 6 characters => "${veryWeakPassword}" has '${veryWeakPassword.length}' characters`
  );
}
// - start with uppercase p, 'P'
else if (!veryWeakPassword.startsWith("P")) {
  console.log(
    `- Password must start with 'P' => it is ${veryWeakPassword.startsWith(
      "P"
    )} that "${veryWeakPassword}" starts with 'P'`
  );
}
// - end with underscore
else if (!veryWeakPassword.endsWith("_")) {
  console.log(
    `- Password must end with '_' => it is ${veryWeakPassword.endsWith(
      "_"
    )} that "${veryWeakPassword}" ends with '_'`
  );
}
// - have uppercase q, 'Q'
else if (!veryWeakPassword.includes("Q")) {
  console.log(
    `- Password must have uppercase q, 'Q' => it is ${veryWeakPassword.includes(
      "Q"
    )} that "${veryWeakPassword}" has 'Q'`
  );
}
// - have lowercase r, 'r'
else if (!veryWeakPassword.includes("r")) {
  console.log(
    `- Password must have lowercase r, 'r' => it is ${veryWeakPassword.includes(
      "r"
    )} that "${veryWeakPassword}" has 'r'`
  );
}
// - have its fifth character as uppercase v, 'V'
// fifth character with have index = fifth position - 1 = 4
// const fifthCharacter = veryWeakPassword[4]
else if (veryWeakPassword.charAt(4) !== "V") {
  console.log(
    `- Password must have its fifth character as uppercase v, 'V' => "${veryWeakPassword}" has its 5th character as '${veryWeakPassword.charAt(
      4
    )}'`
  );
} else {
  console.log(`${veryWeakPassword} is a valid password`);
}

await 告訴 javascript「等待」並從 Promise 接收已解決或已完成的值。

// password validation
const veryWeakPassword = "PrQ1V_";
// const veryWeakPassword = "rtfy67Fg";
// const veryWeakPassword = "OlJgRc__1qwPVa";
console.log(`Password validation for "${veryWeakPassword}"`);

// - be six characters
if (veryWeakPassword.length === 6) {
  if (veryWeakPassword.startsWith("P")) {
    if (veryWeakPassword.endsWith("_")) {
      if (veryWeakPassword.includes("Q")) {
        if (veryWeakPassword.includes("r")) {
          if (veryWeakPassword.charAt(4) === "V") {
            console.log(`${veryWeakPassword} is a valid password`);
          } else {
            console.log(
              `- Password must have its fifth character as uppercase v, 'V' => "${veryWeakPassword}" has its 5th character as '${veryWeakPassword.charAt(
                4
              )}'`
            );
          }
        } else {
          console.log(
            `- Password must have lowercase r, 'r' => it is ${veryWeakPassword.includes(
              "r"
            )} that "${veryWeakPassword}" has 'r'`
          );
        }
      } else {
        console.log(
          `- Password must have uppercase q, 'Q' => it is ${veryWeakPassword.includes(
            "Q"
          )} that "${veryWeakPassword}" has 'Q'`
        );
      }
    } else {
      console.log(
        `- Password must end with '_' => it is ${veryWeakPassword.endsWith(
          "_"
        )} that "${veryWeakPassword}" ends with '_'`
      );
    }
  } else {
    console.log(
      `- Password must start with 'P' => it is ${veryWeakPassword.startsWith(
        "P"
      )} that "${veryWeakPassword}" starts with 'P'`
    );
  }
} else {
  console.log(
    `- Password must have 6 characters => "${veryWeakPassword}" has '${veryWeakPassword.length}' characters`
  );
}

當我們執行上面的程式碼片段時,我們會收到類似以下內容的錯誤:警告:要載入ES 模組,請在package.json 中設定"type": "module" 或使用.mjs 副檔名..

我們可以輕鬆解決這個問題。運行命令 npm init -y。進入 package.json 檔案並新增行“type”:“module”。 package.json 應該類似

// this is a number
const numberOfBirds = 3;

// the above comment is useless since the initial value assigned to the variable
// is physically a number and the variable name also has a number in it
// so use comments wisely by using proper naming

現在,重新運行該程式碼片段,您應該會得到類似於
的輸出

/* 
Everything in here is or will be ignored.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.


*/

const emptyString = "";

現在,假設我們要處理 Promise 拒絕錯誤,如果沒有,我們必須在非同步呼叫周圍使用 try 和 catch 子句。

/**
 * This is a multiline comment
 *
 * But used for documentation
 */

不會有任何 Promise 被拒絕,因為我們設定了 const result = true。將其設為 false。我們的輸出應該類似

const givenNumber = 3;

if (givenNumber % 3 === 0 && givenNumber % 5 === 0) {
  console.log("fizzbuzz");
} else if (givenNumber % 3 === 0) {
  console.log("fizz");
} else if (givenNumber % 5 === 0) {
  console.log("buzz");
}

因此,談論 Promise 以及 async 和 wait 的目的是讓您知道我們會經常這樣做。參考上面列出的非同步操作範例。

async 和await、try 和catch 以及finally 是關鍵字。

結論

至此,我們已經討論了函數和 Promise 以及如何處理它們,我認為我們大約 50% 具備了操縱資料(流)的「知識」。剩下的就是習慣寫 javascript 程式碼並成為一名稱職的 javascript 程式設計師。親自動手使用 JavaScript。這是您編寫後端 API 的唯一方法,並且不會因為您有想法但不知道該怎麼做而感到受到限制。

接下來是編寫一些程式碼並解決一些問題,然後實際開始建立 API。這就是我們接下來要做的,不過,我鼓勵您查看下面的資源。

資源

這些材料有助於理解 Promise、非同步和等待以及事件循環。

  • 事件循環到底是什麼? |菲利普‧羅伯茲 | JSConf 歐盟
  • Node.js 動畫:事件循環
  • JavaScript 視覺化 - 事件循環、Web API、(微)任務佇列
  • JavaScript 在 10 分鐘內實現承諾
  • JavaScript Promise 如何運作 – 初學者教學
這些是一些您想嘗試的練習。

    運動 - javascript
  • jschallenger - javascript 基礎
  • codecademy - 初學者的 10 個 javascript 程式碼挑戰
  • TheOdinProject-javascript-練習
  • codewars - javascript
  • RepublicServicesRepository-javascript-練習
  • leonardomso - 33-js-concepts
  • 這是一本好書,getify - You-Dont-Know-JS
  • 演算法 - Javascript
  • denysdovhan - wtfjs
  • w3schools - js 練習

以上是JavaScript 基礎知識:第 5 部分的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn