JavaScript 필수사항: 5부

Barbara Streisand
풀어 주다: 2024-10-18 20:41:03
원래의
372명이 탐색했습니다.

JavaScript Essentials: Part 5

이전 JavaScript Essentials: Part 4에서 if 및 else 문, for 및 while 루프에 대해 논의했습니다. 이 부분에서는 다음을 살펴보겠습니다.

  • 기능
  • 콜백, 약속, 비동기 및 대기
  • 다음 대작

댓글

댓글은 훌륭하며 이제 이에 대해 이야기하겠습니다. 너무 늦었기 때문에 댓글이 무엇인지 알아야 합니다. 어쨌든 우리 프로그램의 주석은 실행되지 않습니다. 주석은 코드를 문서화하기 위한 것입니다. Javascript에 주석을 추가하는 방법에는 세 가지가 있습니다. 인라인, 멀티라인, 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
 */
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사

댓글은 어디에나 달 수 있습니다. 그러나 코드 줄 뒤(또는 끝)나 코드 아래 또는 위에 배치할 때는 주의하세요.

세미콜론

자바스크립트에서는 세미콜론(;)이 필수는 아니지만 도움이 될 때도 있습니다. 이를 도와주는 도구가 있습니다. 세미콜론은 문의 끝을 나타냅니다. 좋습니다.

톱니 모양

코드를 명확하고 쉽게 읽을 수 있도록 들여쓰기를 사용했습니다. 들여쓰기에는 키보드의 탭 키를 사용합니다. 들여쓰기는 때때로 "탭" 또는 "공백"입니다. 공간은 보통 2~4개 입니다. vscode를 사용하신다면 걱정하지 않으셔도 됩니다.

JavaScript Essentials: Part 4에는 "fizzbuzz", 비밀번호 및 이메일 확인 등을 포함하되 이에 국한되지 않는 몇 가지 연습이 있습니다. 제 의사 코드를 따르면 몇 가지 문제에 직면하게 될 것입니다. 순서를 고려한 스니펫을 제공해드립니다.

단일 숫자에 대한 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`
  );
}
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사

두 스니펫에 대해 어떻게 생각하시나요? 실제로 두 번째 스니펫은 작동하기는 하지만 그다지 훌륭하지는 않습니다.

기능

함수는 재사용할 수 있는 코드 조각입니다. 일반적으로 함수는 특정 작업을 수행합니다. 한 가지. 무엇이든 될 수 있습니다.

자바스크립트에서 함수의 일반적인 형태(구조)를 살펴보겠습니다.

// 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
 */
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사

우리의 무기고를 넓히고 기능을 만드는 것을 재미있게 만드는 방향으로 조금 움직여 봅시다. 두 개의 숫자를 더한 다음 무슨 일이 일어났는지 알려주는 텍스트를 인쇄하는 이 함수를 고려해 보세요.

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");
  }
}
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사

그럼 6과 100을 더하도록 함수를 변경해 보겠습니다. 이제 기능을 변경해야 합니다. 이에 대한 해결책이 있는데, 바로 매개변수(변수를 통한 데이터)를 도입하는 것입니다. 그런 다음 해당 데이터를 인수로 전달합니다.

추가 기능을 분석해 보겠습니다. 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는 함수에서 반환된 값입니다. 그리고 그것은 무엇이든 될 수 있고, 무효한 함수일 수도 있습니다. 너무 걱정하지 마세요. 이전에 작성한 함수 중 일부를 수정하여 작업을 더 간단하게 만들겠습니다.

추가 기능을 기억하시나요? 함수 내부에 값을 기록하는 대신 값을 반환하고 해당 값을 변수에 할당한 다음 나중에 값을 재사용합니다.

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 함수에 대해서도 동일한 작업을 수행합니다.

함수는 반환 가능한 모든 것을 반환할 수 있습니다.

화살표 기능

화살표 함수는 함수를 작성하는 또 다른 방법입니다. 일반적으로 나는 매우 미세한 "일"을 수행하는 간단한 함수가 있거나 반복을 위한 배열 또는 문자열 메서드가 있을 때 화살표 함수를 사용합니다. 함수 선언(이름이 지정된 함수) 대신 이를 사용할 수 있습니다. 함수를 만들고 싶다는 뜻으로 function이라고 말합니다. 화살표 함수는 선언 함수와 동일한 기능을 가지고 있습니다.

화살표 함수는 굵은 화살표 연산자인 => 때문에 호출됩니다. 다음과 같은 형태입니다. 아마도 이전에 본 적이 있을 것입니다.

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
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사

둘의 차이점은 두 번째에서는 블록, { 및 }와 함수에서 값을 반환하는 반환 키워드를 추가했다는 것입니다. 이번에도 값을 반환할지 여부를 선택할 수 있습니다.

함수를 인수로 전달하기

함수를 다른 함수에 인수로 전달할 수 있습니다. 기본적으로 우리는 함수를 값으로 취급합니다. 이 사소한 예를 생각해 보겠습니다.

/* 
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`
  );
}
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사

약속하다

먼저 몇 가지 용어를 정의해 보겠습니다. 우리 틈새시장에서는 약속이 중요합니다.

동기 작업: 위에서 아래로 순차적으로 실행되는 작업입니다. 일부 작업 A1A2의 경우 A1이 완료되어야 A2이 실행됩니다. 이렇게 하면 A2A1까지 실행되지 않습니다. 한 번에 하나의 작업이 실행됩니다. 이러한 단점을 차단이라고 합니다.

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 웹 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
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사

새로움과 약속이 키워드입니다. 해결 및 거부는 콜백 함수입니다. 다른 이름으로 바꿀 수 있습니다. 변환으로 우리는 해결(resolve)과 거부(reject)를 사용합니다.

약속 처리

Promise에는 해결된 값을 제공하는 방법, 거부된 오류를 제공하는 catch 방법, 마지막으로 전체 프로세스를 정리하는 방법이 있습니다. 마지막으로 선택 사항입니다. 다음은 직접 사용해 볼 수 있는 간단한 예입니다.

/* 
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를 살펴보겠습니다.

비동기 및 대기

일반적인 데이터 흐름에서는 비동기 작업이 백그라운드에서 실행되는 것을 원하지 않습니다. 우리는 그것을 듣고 그 결과를 다른 일에 사용하고 싶습니다(당시와 캐치에서 했던 것처럼).

비동기 작업을 만들고 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");
  }
}
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사

이제 어떤 작업이 함수 블록에 들어가고 우리가 만들려는 비동기 함수에서 다른 비동기 작업을 처리해야 한다고 가정해 보겠습니다. 그런 다음 대기를 사용할 수 있습니다.

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는 자바스크립트에게 "대기"하고 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 = "";
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사

이제 약속 거부 오류를 처리하고 싶다고 가정해 보겠습니다. 오류가 없는 경우 비동기 호출 주위에 try 및 catch 절을 사용해야 합니다.

/**
 * This is a multiline comment
 *
 * But used for documentation
 */
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사

const result = true로 설정했기 때문에 약속 거부가 발생하지 않습니다. 거짓으로 설정하세요. 그리고 출력은
과 유사해야 합니다.

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 및 Wait, try and catch 및 finally가 키워드입니다.

결론

기능과 약속, 그리고 이를 처리하는 방법에 대해 논의한 이 시점에서 우리는 데이터(흐름)를 조작할 수 있는 '지식'을 50% 정도 갖추고 있다고 생각합니다. 이제 남은 것은 자바스크립트 코드 작성에 익숙해지고 유능한 자바스크립트 프로그래머가 되는 것입니다. JavaScript로 손을 더럽히십시오. 이것이 백엔드 API를 코딩할 수 있는 유일한 방법이며 아이디어는 있지만 무엇을 해야 할지 모르기 때문에 제약을 받지 않습니다.

다음은 코드를 작성하고 문제를 해결한 후 실제로 API 구축을 시작하는 것입니다. 이것이 우리가 다음에 할 일이지만, 아래 리소스를 확인해 보시기 바랍니다.

의지

프로미스, 비동기, 대기, 이벤트 루프를 이해하는 데 도움이 되는 자료입니다.

  • 이벤트 루프가 도대체 ​​뭐죠? | 필립 로버츠 | JSConf EU
  • Node.js 애니메이션: 이벤트 루프
  • JavaScript 시각화 - 이벤트 루프, 웹 API, (마이크로)작업 대기열
  • JavaScript는 10분 만에 약속합니다
  • JavaScript Promise 작동 방식 – 초보자를 위한 튜토리얼

당신이 직접 해보고 싶은 몇 가지 운동입니다.

  • 운동 - 자바스크립트
  • jschallenger - javascript-basics
  • codecademy - 초보자를 위한 10가지 javascript-code-challenges
  • TheOdinProject-javascript-exercises
  • 코드워 - 자바스크립트
  • RepublicServicesRepository-javascript-exercises
  • leonardomso - 33-js-concepts
  • 읽기 좋은 내용입니다. getify - You-Dont-Know-JS
  • 알고리즘 - 자바스크립트
  • denysdovhan - wtfjs
  • w3schools - js 운동

위 내용은 JavaScript 필수사항: 5부의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!