Published
Edited
Jun 18, 2020
Insert cell
Insert cell
Insert cell
itemList = [] // ["필기도구", "노트북", "충전기"]// 넣어서 해보기
Insert cell
itemList.map( x => "<li>"+x+"</li>" ) // map은 모든 배열에 접근해서 조건대로 새로운 배열을 만들어줌.
Insert cell
itemList.map( x => "<li>"+x+"</li>" ).join("\n") //map으로 모든 배열 요소에 접근한 후 join으로 배열 요소들을 다 감싸준다.
Insert cell
showList2output = () => {
output1.innerHTML = itemList.map( x => "<li>"+x+"</li>" ).join("\n")
}
Insert cell
output1 = html`<ul></ul>` //(연습용)
Insert cell
// showList2output(itemList)
Insert cell
Insert cell
itemList2 = ["필기도구", "노트북", "충전기"]
Insert cell
itemList2.find( x => x==="필기도구" )
Insert cell
itemList2.find( x => x==="타임머신" )
Insert cell
Insert cell
{ // undefined, null, "", 0, false가 아닌 정상적인 값은 조건검사에서 true와 같이 동작
if ("필기도구") { return "T" }
else { return "F" }
}
Insert cell
{ // undefiend, null, "", 0도 조건검사에서 false와 같이 동작
if (undefined) { return "T" }
else { return "F" }
}
Insert cell
addList = (x) => {
// 중복이 되지 않게 출력하는 방법(공백도 포함)
if ( x==="" || itemList.find( element => element ===x ) ) return // 빈 문자열 이거나 이미 목록에 있으면 그냥 아무것도 안하고 리턴
else itemList.push(x) // 찾지 못한 경우에만 새롭게 목록에 추가
}
Insert cell
output = html`<ul></ul>` // 준비물 목록을 리스트 아이템으로 출력할 곳 (연습용)
Insert cell
/* {
addList("라면")
addList("라면")
addList("라면")
addList("라면")
addList("생수")
addList("생수")
addList("생수")
addList("")
addList("")
addList("")
showList1output() // Part1 영상에서 만들었던 showList 함수와는 다른 함수가 필요하므로 이름을 이걸로 수정
} */
Insert cell
showList1output = () => {
output.innerHTML = itemList.map( x => "<li>"+x+"</li>" ).join("\n")
}
Insert cell
Insert cell
btn = html`<button style="width: 100px; height: 50px; ">버튼</button>`
Insert cell
bgChange = (e) => {
const random = n => Math.floor( Math.random() * n ) // 렌덤함수정의
const rndCol = 'rgb(' + random(256) + ',' + random(256) + ',' + random(256) + ')';
console.log(rndCol)
e.target.style.backgroundColor = rndCol; // 책에 강조해서 소개되지 않지만 꼭 알아둘 내용: Event 객체의 target 속성 ,
console.log(e);
//e.target은 내가 지금 버튼을 클릭했는데 이 이벤트가 뭔지, 어디서 발생하고 있는지 알려주는 부분. 중요!!!! 이것을 사용하면 function bgChange(e) {...} 이렇게 안쓰고 ES6 버전인 bgChange = (e) => {...}이렇게 쓸수 있다. 책에는 e.target이 this로 되어있다.
}
Insert cell
btn.onclick = bgChange
Insert cell
Insert cell
doc = html`
<div>
<input id="item">
<button id="add">추가</button>
<ul id="listItem"></ul>
</div>
`
Insert cell
doc.querySelector("#item").value
Insert cell
addBtn = doc.querySelector("#add")
Insert cell
addBtn.onclick = () => {
const item = doc.querySelector("#item").value
addList( item )
showList() // 변경 내용을 다시 UI에 나타내기 위해
}
Insert cell
showList = {
const showList = () => {
const ul = doc.querySelector("#listItem")
ul.innerHTML = // <li><button data-item='라면'>x</button>라면</li>
itemList.map( item => "<li><button data-item='"+item+"'>x</button>"+item+"</li>" ).join("\n")
// 버튼에 대한 이벤트 핸들러 등록
ul.querySelectorAll("button").forEach( b => b.onclick = (e) => {
removeList(e) // forEach로 각각의 버튼에 이벤트를 다 등록해서 각각의 X버튼이 동작하도록 설정
showList() // 변경된 내용을 UI에 나타내기 위해
})
}
return showList
}
Insert cell
html`data-item=은 제거할 때 지울 목록의 아이템 이름을 버튼에 넣어주어 다른 버튼과 구별하기 쉽게하고 indexOf로 인덱스를 가져와서 삭제해줄 때 사용하는 것이다.`
Insert cell
ul = doc.querySelector("#listItem")
Insert cell
/*itemList.splice(index, 1) // index 위치의 1개만 삭제
ul
li li li
btn 물건1이름 btn 물건2이름 btn 물건3이름
*/
ul.children
Insert cell
// 셀렉터의 강력한 능력을 소환 - ul 안에 있는 모든 button을 선택
ul.querySelectorAll("button")
Insert cell
Insert cell
removeList = (e) => {
// console.log("removeList")
// console.log(e)

const xbtn = e.target // 이벤트가 발생한 곳 (x버튼)
const index = itemList.indexOf(xbtn.dataset.item) // 지울 물건의 index 얻기
// indexOf는 item이 배열의 몇번째 위치에 있는지 숫자로 나타내줌
if ( index < 0 ) return // 비정상적 상황 (이런 일은 일어나면 안됨)
itemList.splice(index, 1) // index 위치의 1개만 삭제
}
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more