본문 바로가기
개념/혼자 공부하는 Javascript

chapter 6) Add object properties dynamically

by kiseno 2024. 12. 15.
728x90
반응형
SMALL
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        //add
        const student = {}
        student.name = 'insung'
        student.hobby = 'playing'
        student.future = 'bio-logical engineer'

        console.log(JSON.stringify(student, null, 2))


        //delete
        const student2 = {}
        student2.name = 'insung'
        student2.hobby = 'playing'
        student2.future = 'bio-logical engineer'

        delete student2.future
        console.log(JSON.stringify(student, null, 2))

    </script>
</head>
<body>

</body>
</html>

### Adding Properties to an Object

- **Initialization**: An empty object `student` is created.
- **Adding Properties**: Properties `name`, `hobby`, and `future` are added to the `student` object with respective values `'insung'`, `'playing'`, and `'bio-logical engineer'`.
- **Logging**: `JSON.stringify(student, null, 2)` is used to convert the `student` object into a JSON string with formatting (indentation set to 2 spaces) for readability. This string is logged to the console, showing all added properties and their values.

### Deleting Properties from an Object

- **Initialization**: A similar object `student2` is created with the same properties and values as `student`.
- **Deleting Property**: `delete student2.future` removes the `future` property from the `student2` object.
- **Logging**: The console log mistakenly attempts to log the `student` object again instead of `student2`. To correctly display the modified `student2` object without the `future` property, `JSON.stringify(student2, null, 2)` should be used instead of `JSON.stringify(student, null, 2)`.

### Corrected Logging for `student2`

The correct way to log the `student2` object after deleting the `future` property is:

```javascript
console.log(JSON.stringify(student2, null, 2))
```

This would output the `student2` object to the console, showing the `name` and `hobby` properties only, as the `future` property has been deleted.

### Output

The expected output in the browser's console would be:

For `student` object (before the correction):
```json
{
  "name": "insung",
  "hobby": "playing",
  "future": "bio-logical engineer"
}
```

For `student2` object (after correction):
```json
{
  "name": "insung",
  "hobby": "playing"
}
```

This demonstrates the dynamic nature of JavaScript objects, allowing properties to be easily added and removed. Using `JSON.stringify` with formatting options makes it easier to visually inspect these objects in the console.

728x90
반응형
LIST

'개념 > 혼자 공부하는 Javascript' 카테고리의 다른 글

chapter 7) Manipulating  (1) 2024.12.17
chapter 7) select tag  (0) 2024.12.16
chapter 6) Array_Copy  (0) 2024.12.14
chapter 6) check undefined type  (1) 2024.12.13
chapter 6) href of output script  (0) 2024.12.12