ホームページ  >  記事  >  ウェブフロントエンド  >  JavaScript の基礎: パート 5

JavaScript の基礎: パート 5

Barbara Streisand
Barbara Streisandオリジナル
2024-10-18 20:41:03373ブラウズ

JavaScript Essentials: Part 5

以前、JavaScript Essentials: パート 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 では、セミコロン ; は必要ありませんが、場合によっては役立つことがあります。それを助けるツールがあります。セミコロンはステートメントの終わりを示します。いいですね。

インデント

インデントは、コードをわかりやすく整理し、読みやすくするために使用されます。インデントにはキーボードのタブ キーを使用します。インデントは「タブ」または「スペース」である場合があります。通常、スペースは 2 または 4 です。vscode を使用している場合は、心配する必要はありません。

JavaScript Essentials: Part 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");
}

配列の fizzbuzz

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`
  );
}

2 つの断片についてどう思いますか?実質的に 2 番目のスニペットは、機能しますが、それほど優れたものではありません。

機能

関数は再利用できるコードの一部です。通常、関数は特定のことを行います。一つのこと。何でも構いません。

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 something は、実行したいアクションまたは計算です。関数は通常、何らかの処理が完了した後にデータを返します。そうならない場合もあります。一部のデータを更新するだけで完了です。
  • { // 何かをする } は関数本体またはブロックです

「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
 */

武器の幅を広げ、関数の作成が楽しくなるような方向に少し進んでみましょう。 2 つの数値を加算し、何が起こったかを示すテキストを出力するこの関数について考えてみましょう。

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

「fizzbuzz」についても同じことを行います。スニペットの周囲に関数をラップします。使用される変数についてコメントする必要はありません。どのデータを関数 (入力) に渡す必要があるかを見てください。

関数にはいくつでもパラメータを渡すことができます。ただし、いくつかの制限を設定することをお勧めします。プロの中には3つくらいで十分だという人もいます。 5人未満だという人もいます。賢く対処する必要があります。ここでは、パラメータの数が 3 を超える場合は常に、配列またはオブジェクトを使用するとします。うん。配列またはオブジェクトを引数として渡すことができます。

/* 
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 は関数から返される値です。そして、それは何から何まで、つまり void 関数である可能性があります。汗をかかないでください。以前に作成したこれらの関数の一部を変更して、作業を簡素化します。

追加関数を覚えていますか?関数内の値をログに記録する代わりに、値を返し、その値を変数に代入し、後でその値を再利用します。

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 関数に対しても同じことを行います。

関数は返せるものであれば何でも返すことができます。

アロー関数

アロー関数は、関数を記述するもう 1 つの方法です。通常、非常に細かい「こと」を実行する単純な関数がある場合、またはループ用の配列または文字列メソッドでアロー関数を使用します。関数宣言 (名前付き関数) の代わりに使用できます。関数を作成したいことを示すために、「関数」と言います。アロー関数には宣言関数と同じ機能があります。

アロー関数は、太い矢印演算子である => のためにそのように呼ばれます。これは、おそらく以前に見たことがある形式です:

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

2 つの違いは、2 つ目では、ブロック { と } と、関数から値を返す 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 = "";

これを実行できるもう 1 つの場所は、配列メソッドまたは文字列メソッドを使用することです。この関数を検討してください

/**
 * 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");
  }
}

最後のパラメータはデフォルトパラメータと呼ばれ、通常は
として配置されます。 最後の引数。これは、もしそうするなら必ずしなければならないことです
デフォルト値を使用します。このスニペットは前のスニペットとそれほど変わりません
1 つは、デフォルト パラメーターの導入を除いて、3 番目の
を意味します。 引数に値を渡すかどうかを選択できます。

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`
  );
}

約束

その前に、いくつかの用語を定義しましょう。私たちのニッチ分野では約束が重要です。

同期操作: これらは、上から下に順番に実行される操作です。一部の操作 A1 および A2 では、A2 が実行される前に A1 が完了する必要があります。こうすることで、A2A1 まで実行されなくなります。一度に 1 つの操作が実行されます。この欠点はブロッキングと呼ばれます。

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

上記の出力は、上で説明したように線形順序になっています。

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

つまり、これまでに作成したコードはすべて同期順序で実行され、1 行がいつ実行されるかがわかります。

非同期操作: これらは、順番に実行されない操作です。これらの操作は同時に実行されます。これらは、実際には少しずつ同時に実行される複数の操作である可能性があります。 1 つの操作の成功または実行は順序とは無関係であり、他の行の実行を妨げないため、この動作をノンブロッキングと呼びます。非同期行がいつ実行されるかはわかりません。

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 は、非同期操作を管理または処理するための手段を提供します。これは、非同期操作がいつ実行されるか、非同期操作が「完了」したか失敗したかを知る方法です。

約束を作成しましょう

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

新しいと約束がキーワードです。解決と拒否はコールバック関数です。他の名前に置き換えることもできます。変換では、解決と拒否を使用します。

約束を処理する

Promise には、解決された値を提供する then メソッド、拒否されたエラーを提供する catch メソッド、そしてプロセス全体の後にクリーンアップする方法である Final があります。ただし、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 と await を見てみましょう。

非同期で待機する

通常のデータ フローでは、非同期操作がバックグラウンドで実行されることは望ましくありません。これを聞いて、その結果を使って何か他のことをしたいと考えています (then と catch で行ったように)。

非同期操作を作成し、async と await を使用して処理しましょう。

私たちは名前付き関数とアロー関数を作成する方法を知っています。

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
 */

const result = true に設定しているため、Promise の拒否は発生しません。 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 と await について話す目的は、それを頻繁に行うことを知らせることです。上記の非同期操作の例を参照してください。

async と await、try and catch、finally がキーワードです。

結論

関数とプロミスとその処理方法について説明したこの時点で、データ (フロー) を操作するための「知識」は 50% ほど備わっていると思います。残っているのは、JavaScript コードの作成に慣れて、有能な JavaScript プログラマーになることです。 JavaScript を実際に使ってみましょう。これが、アイデアはあっても何をすればよいかわからないという制約を感じずにバックエンド API をコーディングできる唯一の方法です。

次に、コードを作成して問題を解決し、実際に API の構築を開始します。これが私たちが次に行うことですが、以下のリソースをチェックすることをお勧めします。

リソース

これらは、Promise、async と await、イベント ループを理解するのに役立つ資料です。

  • そもそもイベントループとは一体何なのでしょうか? |フィリップ・ロバーツ | JSConf EU
  • Node.js アニメーション: イベント ループ
  • 視覚化された JavaScript - イベント ループ、Web API、(マイクロ)タスク キュー
  • JavaScript は 10 分で終わると約束します
  • JavaScript の仕組み – 初心者向けチュートリアル

これらは、実際に試してみたいいくつかのエクササイズです。

  • 演習 - JavaScript
  • jschallenger - javascript-basics
  • codecademy - 初心者のための 10 の JavaScript コードチャレンジ
  • TheOdinProject-javascript-演習
  • コードウォーズ - JavaScript
  • RepublicServicesRepository-javascript-exercises
  • leonardomso - 33-js-concepts
  • これは良い読み物です。getify - You-Dont-Know-JS
  • アルゴリズム - JavaScript
  • デニスドフハン - wtfjs
  • w3schools - js 演習

以上がJavaScript の基礎: パート 5の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。