티스토리 뷰

Timestamp 타임스탬프

  • 현재 시간 또는 특정 시간을 가져온다
  • 일반적으로 1970년 1월 1일 00:00:00 (UTC)로부터 경과한 밀리초(milliseconds) 또는 초 단위로 시간을 나타낸다

 

팀과제 중 로컬스토리지를 이용한 댓글 구현 항목 중 삭제 기능을 구현하려면 로컬스토리지에 삭제 '기준'을 만들어서 삭제해줘야 했는데 작성자, 비밀번호는 중복이 허용되기 때문에 적합하지 않았다.

대신 타임스탬프를 이용하여 id대신 고유의 값으로 사용하기로 했다

 

  • 댓글 생성 시 new Date를 id변수에 담아 생성된 댓글마다 타임스탬프를 넣어준다.
  // 댓글 객체 생성(작성자, 댓글 내용, 비밀번호)
  const id = Date.now(); // 댓글 삭제를 위한 id값
  const makeComment = {
    userName: userName.value,
    comment: comment.value,
    pw: pw.value,
    id
  };

 

 

  • 댓글 목록을 뿌리는 forEach에 댓글 아이디를 넣어줌으로 댓글 목록에도 id값이 들어가게 된다.
 // 댓글 목록 화면에 뿌리기
  allComments.forEach(comment => {
    const commentElement = document.createElement('li');
    commentElement.innerText = `${comment.comment} - ${comment.userName}`;
    commentElement.dataset.userName = comment.userName;
    commentElement.dataset.id = comment.id;
    const deleteBtn = document.createElement('button');
    deleteBtn.className = 'deleteBtn';
    deleteBtn.innerText = '삭제';
    commentElement.appendChild(deleteBtn);
    commentBox.appendChild(commentElement);
    console.log(comment)
  });
}

 

 

  • id가 필요했던 이유, 댓글 삭제 기능에서 삭제 이벤트를 받을 댓글과, id를 가져왔다
// 이벤트 대상의 클레스가 deleteBtn이면 작동
  if (e.target.classList.contains('deleteBtn')) {

const commentElement = e.target.parentElement; // 이벤트 대상(삭제 대상)의 부모 요소를 변수에 담음
const id = commentElement.dataset.id; // 이벤트 대상(삭제 대상)의 id값을 변수에 담음

 

 

  • 댓글 목록을 가져오고, find를 이용해 댓글 목록의 id값과, 이벤트 대상의 id값이 같은 대상을 찾아준다
// 댓글 가져오기
    const comments = JSON.parse(localStorage.getItem(clickedMovieId));

const comment = comments.find(function (comment) {
	return String(comment.id) === id
    });

 

 

  • filter 메서드를 사용하여 댓글의 id와 삭제 이벤트 대상의 id가 같지 않는 것만 반환하여 로컬스토리지에 다시 저장해 주면 삭제대상인 댓글만 지워지고 다른 댓글들은 남아있게 된다.
// 필터를 통해 댓글의 id와 이벤트 대상의 id가 같지 않은것만 반환한다(id값이 같은 대상은 삭제)
      let filteredComments = comments.filter(function (comment) {
        return String(comment.id) !== id
      });
      // console.log("filteredComments",filteredComments)

      // 필터로 이벤트 대상이 아닌 id값만 모인 댓글은 로컬스토리지에 다시 저장해준다.
      localStorage.setItem(clickedMovieId, JSON.stringify(filteredComments));
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함