JavaScript 할당 연산자 탐구

HTMLBeginner
지금 연습하기

소개

이 랩에서는 학생들이 실습 HTML 및 JavaScript 연습을 통해 JavaScript 할당 연산자를 탐구합니다. 이 랩은 학습자가 HTML 파일을 생성하고 기본 할당 (=), 복합 할당 (+=, -=), 곱셈/나눗셈 할당 (*=, /=) 을 포함한 다양한 할당 연산자를 구현하는 과정을 안내합니다.

참가자는 임베디드 스크립트 태그를 사용하여 HTML 구조를 설정하는 것으로 시작한 다음, 다양한 할당 연산자 기술을 점진적으로 시연합니다. console logging 및 document.write() 메서드를 사용하여 학생들은 이러한 연산자가 JavaScript 에서 어떻게 작동하는지 확인하고 이해하며, 변수 조작 및 값 할당에 대한 실질적인 경험을 얻게 됩니다.

JavaScript 할당 연산자를 위한 HTML 파일 생성

이 단계에서는 JavaScript 할당 연산자를 탐구하기 위한 기반이 될 HTML 파일을 생성합니다. HTML 은 JavaScript 코드를 임베딩하기 위한 구조를 제공하여 다양한 할당 연산자 기술을 시연하고 테스트할 수 있도록 합니다.

먼저 WebIDE 를 열고 ~/project 디렉토리로 이동합니다. 파일 탐색기에서 마우스 오른쪽 버튼을 클릭하고 "New File"을 선택하여 assignment-operators.html이라는 새 파일을 생성합니다.

다음은 사용할 기본 HTML 구조입니다.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>JavaScript Assignment Operators</title>
  </head>
  <body>
    <h1>Exploring Assignment Operators</h1>

    <script>
      // JavaScript code will be added here in subsequent steps
    </script>
  </body>
</html>

주요 구성 요소를 살펴보겠습니다.

  • <!DOCTYPE html>은 이것을 HTML5 문서로 선언합니다.
  • <script> 태그는 JavaScript 코드를 작성할 위치입니다.
  • 페이지에는 컨텍스트를 제공하기 위한 간단한 제목이 포함되어 있습니다.

파일을 생성한 후 ~/project 디렉토리에 저장합니다. 이 HTML 파일은 다음 단계에서 할당 연산자에 대해 배우기 위한 우리의 놀이터가 될 것입니다.

이 파일을 브라우저에서 열 때의 예시 출력:

Exploring Assignment Operators

기본 할당 연산자 (=) 구현

이 단계에서는 JavaScript 의 기본 할당 연산자 (=) 에 대해 배우게 됩니다. 할당 연산자는 변수에 값을 할당하는 데 사용되며, 데이터를 저장하고 조작하는 기본적인 방법을 제공합니다.

이전 단계에서 생성한 assignment-operators.html 파일을 엽니다. <script> 태그 안에 다음 JavaScript 코드를 추가하여 기본 할당을 탐구합니다.

// Declaring and assigning variables using the = operator
let firstName = "John";
let age = 25;
let isStudent = true;

// Demonstrating variable assignment
console.log("First Name:", firstName);
console.log("Age:", age);
console.log("Is Student:", isStudent);

주요 개념을 살펴보겠습니다.

  • let은 최신 JavaScript 에서 변수를 선언하는 데 사용됩니다.
  • = 연산자는 변수에 값을 할당합니다.
  • 변수는 문자열, 숫자 및 부울 값과 같은 다양한 유형의 데이터를 저장할 수 있습니다.
  • console.log()는 값을 브라우저의 콘솔에 출력하는 데 사용됩니다.

같은 연산자를 사용하여 변수를 다시 할당할 수도 있습니다.

// Reassigning variable values
age = 26;
console.log("Updated Age:", age);

// Assigning the value of one variable to another
let originalAge = age;
console.log("Original Age:", originalAge);

브라우저 콘솔의 예시 출력:

First Name: John
Age: 25
Is Student: true
Updated Age: 26
Original Age: 26

복합 할당 연산자 (+=, -=) 연습

이 단계에서는 JavaScript 에서 복합 할당 연산자 +=-=에 대해 알아보겠습니다. 이러한 연산자는 변수에 새로운 값을 할당하면서 덧셈과 뺄셈을 수행하는 단축 방법을 제공합니다.

assignment-operators.html 파일을 열고 <script> 태그 안에 다음 JavaScript 코드를 추가합니다.

// Initial variable declaration
let score = 100;
console.log("Initial Score:", score);

// Using += operator to add and assign
score += 50; // Equivalent to: score = score + 50
console.log("Score after +50:", score);

// Using -= operator to subtract and assign
score -= 25; // Equivalent to: score = score - 25
console.log("Score after -25:", score);

// Practicing with another variable
let quantity = 10;
console.log("Initial Quantity:", quantity);

quantity += 5; // Add 5 to quantity
console.log("Quantity after +5:", quantity);

quantity -= 3; // Subtract 3 from quantity
console.log("Quantity after -3:", quantity);

복합 할당 연산자에 대한 주요 사항:

  • +=는 오른쪽 값과 변수를 더하고 결과를 할당합니다.
  • -=는 오른쪽 값을 변수에서 빼고 결과를 할당합니다.
  • 이러한 연산자는 변수 값을 수정하는 더 간결한 방법을 제공합니다.
  • 숫자와 함께 작동하며 산술 연산을 단순화할 수 있습니다.

브라우저 콘솔의 예시 출력:

Initial Score: 100
Score after +50: 150
Score after -25: 125
Initial Quantity: 10
Quantity after +5: 15
Quantity after -3: 12

곱셈 및 나눗셈 할당 연산자 (*=, /=) 시연

이 단계에서는 JavaScript 에서 곱셈 및 나눗셈 할당 연산자 *=/=에 대해 알아보겠습니다. 이러한 연산자는 변수를 곱하거나 나누고 결과를 다시 동일한 변수에 할당하는 간결한 방법을 제공합니다.

assignment-operators.html 파일을 열고 <script> 태그 안에 다음 JavaScript 코드를 추가합니다.

// Multiplication assignment operator (*=)
let price = 10;
console.log("Initial Price:", price);

price *= 3; // Equivalent to: price = price * 3
console.log("Price after *3:", price);

// Division assignment operator (/=)
let quantity = 24;
console.log("Initial Quantity:", quantity);

quantity /= 4; // Equivalent to: quantity = quantity / 4
console.log("Quantity after /4:", quantity);

// Practical example: Calculating total cost
let itemPrice = 5;
let itemCount = 7;
console.log("Item Price:", itemPrice);
console.log("Item Count:", itemCount);

let totalCost = itemPrice * itemCount;
console.log("Total Cost:", totalCost);

totalCost *= 0.9; // Apply 10% discount
console.log("Discounted Total Cost:", totalCost);

곱셈 및 나눗셈 할당 연산자에 대한 주요 사항:

  • *=는 변수에 오른쪽 값을 곱하고 결과를 할당합니다.
  • /=는 변수를 오른쪽 값으로 나누고 결과를 할당합니다.
  • 이러한 연산자는 수학적 연산과 할당을 단순화하는 데 도움이 됩니다.
  • 숫자 값과 함께 작동하며 다양한 계산에 사용할 수 있습니다.

브라우저 콘솔의 예시 출력:

Initial Price: 10
Price after *3: 30
Initial Quantity: 24
Quantity after /4: 6
Item Price: 5
Item Count: 7
Total Cost: 35
Discounted Total Cost: 31.5

document.write() 를 사용하여 할당 연산자 결과 확인

이 단계에서는 document.write()를 사용하여 할당 연산자의 결과를 웹 페이지에 직접 표시하는 방법을 배우게 됩니다. 이 방법은 초보자가 JavaScript 연산을 시각화할 수 있도록 값을 출력하는 간단한 방법을 제공합니다.

assignment-operators.html 파일을 열고 <script> 태그를 수정하여 다음 코드를 포함합니다.

// Demonstrating assignment operators with document.write()
let initialValue = 10;
document.write("<h2>Assignment Operator Demonstration</h2>");
document.write("Initial Value: " + initialValue + "<br>");

// Basic assignment
initialValue = 20;
document.write("After Basic Assignment (=): " + initialValue + "<br>");

// Compound addition assignment
initialValue += 5;
document.write("After Addition Assignment (+=): " + initialValue + "<br>");

// Compound subtraction assignment
initialValue -= 3;
document.write("After Subtraction Assignment (-=): " + initialValue + "<br>");

// Multiplication assignment
initialValue *= 2;
document.write(
  "After Multiplication Assignment (*=): " + initialValue + "<br>"
);

// Division assignment
initialValue /= 4;
document.write("After Division Assignment (/=): " + initialValue + "<br>");

document.write()에 대한 주요 사항:

  • HTML 또는 텍스트를 웹 페이지에 직접 작성합니다.
  • 변수 값을 표시하는 데 사용할 수 있습니다.
  • JavaScript 연산을 디버깅하고 시연하는 데 유용합니다.
  • 호출된 순서대로 페이지에 콘텐츠를 추가합니다.

브라우저의 예시 출력:

Assignment Operator Demonstration
Initial Value: 10
After Basic Assignment (=): 20
After Addition Assignment (+=): 25
After Subtraction Assignment (-=): 22
After Multiplication Assignment (*=): 44
After Division Assignment (/=): 11

요약

이 Lab 에서 참가자들은 실습 HTML 및 JavaScript 연습을 통해 JavaScript 할당 연산자를 탐구합니다. Lab 은 문자열, 숫자, 부울과 같은 다양한 데이터 유형으로 변수를 선언하고 초기화하는 기본 할당 연산자 (=) 부터 시작하여 다양한 할당 연산자 기술을 시연하기 위한 기반 역할을 하는 HTML 파일을 생성하는 것으로 시작합니다.

학습 과정은 산술 연산을 수행하고 변수 값을 업데이트하는 간결한 방법을 제공하는 +=, -=, *=, /=와 같은 복합 할당 연산자를 구현하는 것으로 진행됩니다. document.write() 및 console.log() 를 사용하여 참가자들은 이러한 할당 연산의 결과를 확인하고 시각화하여 이러한 연산자가 JavaScript 프로그래밍에서 어떻게 작동하는지에 대한 실질적인 이해를 얻을 수 있습니다.