<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
function createsStudent(name,kor,eng,math,sci){
return {
name: name,
kor: kor,
eng: eng,
math: math,
sci: sci,
getSum() {
return this.kor + this.eng + this.math + this.sci
},
getAverage() {
return this.getSum() / 4
},
toString(){
return `${this.name}\t${this.getSum()}\t${this.getAverage()}\n`
}
}
}
const students = []
students.push(createsStudent('cloud',83,63,95,83))
students.push(createsStudent('star',80,89,97,32))
students.push(createsStudent('winter',98,96,54,83))
students.push(createsStudent('fall',80,42,98,99))
let output = `name\tsum\taverage\n`
for (const s of students){
output += s.toString()
}
console.log(output)
</script>
</head>
<body>
</body>
</html>
1. **`createsStudent` Function**: This function is crafted to generate an object for each student, provided with attributes for their name and scores across four subjects (Korean, English, Math, and Science). It returns an object containing:
- The student's name and their subject scores as object properties.
- A `getSum` method that computes the sum of scores across the four subjects.
- A `getAverage` method that calculates the average score by dividing the total score (`getSum`) by 4.
- A `toString` method designed to return a formatted string including the student's name, their total score, and their average score.
2. **Creating and Populating the `students` Array**: The script initializes an empty array named `students` to store student objects. It then populates this array with four student objects created using the `createsStudent` function, each with predefined names and scores.
3. **Generating and Logging the Output**: The script initializes a string variable `output` with column headers "name", "sum", and "average", accurately reflecting the subsequent data. It iterates over the `students` array, appending each student's data (formatted by their `toString` method) to the `output` string. This resulting string is then logged to the console.
This corrected script effectively logs a table to the console, listing each student's name, their total score across subjects, and their average score, with the header correctly reflecting the columns as "name", "sum", and "average". The `toString` method ensures that each student's data is formatted appropriately for this table.
'개념 > 혼자 공부하는 Javascript' 카테고리의 다른 글
function) confirm() (0) | 2025.01.27 |
---|---|
function) prompt() (0) | 2025.01.26 |
method) private (1) | 2025.01.24 |
class) Ractangle class (0) | 2025.01.23 |
method) forEach() (1) | 2025.01.22 |