Published
Edited
Jun 7, 2020
Insert cell
/* 주어진 문제*/
doc = html`
<div>
<select name="cars">
<option value="sum">총합</option>
<option value="avg">평균</option>
<option value="dev">표준편차</option>
</select>
<output>0</output>
<div><button type="button" id="add">+</button></div>
</div>
`
Insert cell
/* cloneNode로 사용되는 셀 */
cell0 = html`<div class="cell"><button type="button">x</button><input type="number" value="0"></div>`
Insert cell
doc.querySelector("#add").addEventListener("click", addCell) // (id가 add인) + 버튼에 등록할 이벤트 핸들러
Insert cell
addCell = () => {
const cell = cell0.cloneNode(true) // 새로운 셀 추가
cell.querySelector("button").addEventListener("click", delCell) // 새로운 셀 x 버튼에 등록할 삭제 이벤트 핸들러
doc.appendChild(cell)
calc() // 변경된 값을 즉시 적용하기 위한 함수
}
Insert cell
delCell = e => {
e.target.parentNode.remove() // 부모 노드를 타겟으로 지정하여 삭제
calc() // 변경된 값을 즉시 적용
}
Insert cell
doc.addEventListener("change", calc) // 값을 변경할 때마다 결과값을 변경할 이벤트 핸들러
Insert cell
// 값을 계산하고 반환하는 함수
calc = () => {
const output = doc.querySelector("output") // ouput 지정 -> HTML 문서 output 태그 지정
const vs = Array.from(doc.querySelectorAll(".cell > input")).map(i => parseInt(i.value)) //cell 클래스 안의 모든 input의 인덱스 지정
const sum = vs.reduce((x, y) => x+y, 0) // 총합 계산
const avg = sum / vs.length // 평균 계산
const dev = Math.sqrt(vs.map(v => (v-avg)**2) .reduce((x, y) => x+y, 0)/vs.length) // 표준편차 계산

switch (doc.querySelector("select").value) { // select된 값에 따라 반환할 값 설정
case "sum" : output.value = sum; break
case "avg" : output.value = avg; break
case "dev" : output.value = dev; break
}
}
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