본문 바로가기

Computer/HTML, CSS, Javascript

[Javascript] 과제: 함수

https://developer.mozilla.org/ko/docs/Learn/JavaScript/Building_blocks/Test_your_skills:_Functions

 

실력을 평가해 보세요: 함수 - Web 개발 학습하기 | MDN

이 실력 테스트의 목적은 여러분이 우리의 함수 — 코드 재사용, 함수 만들기, 그리고 함수 반환 값 문서를 이해했는지 평가하기 위함입니다.

developer.mozilla.org

 

함수1

names의 아무 name을 무작위로 나타내는 문제였다.

const names = ['Chris', 'Li Kang', 'Anne', 'Francesca', 'Mustafa', 'Tina', 'Bert', 'Jada']
const para = document.createElement('p');

// Add your code here
function chooseName() {
  return names[Math.floor(Math.random()*names.length)];
};
para.textContent = chooseName();
// Don't edit the code below here!

section.innerHTML = ' ';

section.appendChild(para);

 

결과(예시)

함수1 결과물

함수2

  • x — 직사각형의 x 좌표.
  • y — 직사각형의 y 좌표.
  • width — 직사각형의 너비.
  • height — 직사각형의 높이.
  • color — 직사각형의 색깔.

이를 바탕으로 캔버스를 그리는 함수를 만들어야 하는 문제였다.

canvas 태그는 다룬 적이 없어서 https://developer.mozilla.org/ko/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes, https://developer.mozilla.org/ko/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors 이 사이트를 참고하였다.

const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');

const x = 50;
const y = 60;
const width = 100;
const height = 75;
const color = 'blue';

// Add your code here
function drawCanvas (x, y, w, h, c) {
  ctx.fillRect(x, y, w, h);
  ctx.fillStyle = c;
}

drawCanvas(x, y, width, height, color);

 

결과

함수2 결과

함수3

함수1의 과제를 숫자를 무작위로 선택하는 부분을 따로 함수로 만들어서 리팩토링 해야 했다.. 코드는 아래와 같다.

 

const names = ['Chris', 'Li Kang', 'Anne', 'Francesca', 'Mustafa', 'Tina', 'Bert', 'Jada']
const para = document.createElement('p');

// Add your code here
function random(min, max) {
  return Math.floor(Math.random()*max - min);
}

function chooseName(arr) {
  return arr[random(0, arr.length)];
}

para.textContent = chooseName(names);

// Don't edit the code below here!

section.innerHTML = ' ';

section.appendChild(para);

 

결과

'함수3 결과물

 

 

 

 

오류 있으면 댓글 남겨주세요. 감사합니다!!

728x90

'Computer > HTML, CSS, Javascript' 카테고리의 다른 글

[Javascript] 과제: 객체  (4) 2024.12.28
[Javascript] 과제: 반복문  (1) 2024.12.04
[Javascript] 과제: 조건  (3) 2024.10.27
[Javascript] 과제: 배열  (1) 2024.10.25
[Javascript] 과제: Silly story generator  (0) 2024.10.25