Dseok의 실전 예제로 웹개발 한방에 끝내기

웹개발, 혼자 하려니 막막하고 힘드시죠? 저 또한 그렇습니다. 힘든 웹개발... 실전 예제를 통해 함께 공부해요!!!!😁📕

Javascript

[Dseok의 코딩스터디] javascript / javascript join() Method / 자바스크립트 join() / Array.prototype.join()

Dseok 2023. 8. 3. 00:10
반응형
SMALL

Array.prototype.join()에 대해서 알아보자.

우선 MDN의 설명이다.

join()
메서드는 배열의 모든 요소를 연결해 하나의 문자열로 만듭니다.

join()메소드는 설명이 쉽게 되어있는 듯 하여 추가적인 설명은 하지 않겠다.

 

먼저 join()의 문법을 알아보자.

arr.join([separator])

join()메서드는 인자로 문자열을 받는다.

이 문자열은 배열의 각 원소 사이에 반복적으로 반영된다.

예를 들면 띄어쓰기라던지, 하이픈( - )이라던지 이런 것들을 넣을 수 있다.

 

바로 예시를 알아보자.

const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// Expected output: "Fire,Air,Water"

console.log(elements.join(''));
// Expected output: "FireAirWater"

console.log(elements.join('-'));
// Expected output: "Fire-Air-Water"

 

바로 다음 예시를 알아보자.

var a = ['바람', '비', '불'];
var myVar1 = a.join();      // myVar1에 '바람,비,불'을 대입
var myVar2 = a.join(', ');  // myVar2에 '바람, 비, 불'을 대입
var myVar3 = a.join(' + '); // myVar3에 '바람 + 비 + 불'을 대입
var myVar4 = a.join('');    // myVar4에 '바람비불'을 대입

 

조금 더 복잡하게 생각해보자.

객체에서도 활용이 된다.

const users = [
  { id: 1, name: 'Alice', age: 25 },
  { id: 2, name: 'Bob', age: 30 },
  { id: 3, name: 'Charlie', age: 22 }
];
const names = users.map(user => user.name);
const namesString = names.join(', ');
console.log(namesString); // Output: "Alice, Bob, Charlie"

map이라는 것이 들어가는데... 이건 반복문과 비슷하다고 보면 된다.

추후에 정리하겠다..

 

자, 이제 사용법에 대한 이해가 어느정되 되었으리라고 믿겠다.

 

join()을 활용 할 수 있는 곳을 대표적으로 보자.

 

1. 날짜 구분하기(년,월,일).

2. 태그를 이용한 문자열 생성.

3. css 클래스 조건부 적용.

4. To Do List 데이터 가져오기.

 

일단은 이 정도만 알아보자.

 

실제로 구현 해볼 예시는 4. To Do List 데이터 가져오기. 이다.

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="keywords" content="basic" />
    <meta name="description" content="basic" />
    <link rel="shortcut icon" href="" />
    <link rel="stylesheet" href="./css/reset.css">
    <link rel="stylesheet" href="./css/index.css">
    <title>basic</title>
</head>
<body>
    <h1>To-Do List</h1>
    <ul id="todoList"></ul>
    <script src="./js/jquery-3.6.0.min.js"></script>
    <script src="./js/index.js"></script>
</body>
</html>

 

@charset "UTF-8";
body {
  font-family: Arial, sans-serif;
  margin: 20px;
}

h1 {
  text-align: center;
  font-weight: bold;
  font-size: 50px;
}

ul {
  list-style: none;
  padding: 0;
  width: 50%;
  margin: 80px auto 0;
  text-align: center;
}

li {
  margin-bottom: 10px;
  text-align: center;
}

 

const tasks = ['Buy groceries', 'Clean the house', 'Walk the dog', 'Read a book'];

function 배열에서데이터가져오는함수(items) {
  const todoList = document.getElementById('todoList');
  const listItems = items.map(item => `<li>${item}</li>`).join('');
  todoList.innerHTML = listItems;
}

배열에서데이터가져오는함수(tasks);

이렇게 하면 사용자가 리스트를 입력했을 때 데이터를 동적으로 가져와서 li에 넣을 수 있다.

반응형
LIST