Published
Edited
May 6, 2020
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
// change-1
// doc01은 전체 셀에 이름을 붙여주는 것. 즉 전역변수임. 다른 셀에서도 사용가능ObservableHQ의 기능이며 js기능 아님.
doc01 = html`
<div> //하나의 오브젝트로 생각
<h2 id="heading01">자바스크립트</h2>
<p id="text">위 텍스트를 클릭해 보세요</p>
</div>
`
Insert cell
{
let heading = doc01.querySelector('#heading01')//doc01로 접근하고 querySelector메소드의 인자 heading01는 div안에 id가 heading01인 엘레멘트를 선택하게 됨.
heading.onclick = () => { //클릭을 하면 어떤 행동을 하라는 메소드
heading.style.color = "red" // 위 h2에 해당하는 자바스트립트의 색상을 red로 바꾸라는 얘기
//자바스크립트는 처음에는 기본색깔로 되어 있는 문서였는데 사용자가 클릭을 하면 어떤 반응을 보이고 동적으로 색상을 변경하고 내용을 바꾸는 것으로 일단 이해해라.
}
}
Insert cell
// 참고로 ObservableHQ 노트북에서는 다른 셀에 정의된 지역변수를 참조할 수는 없다
mycell = heading
Insert cell
doc02 = html`
<h2>환영합니다</h2>
<input>
<button>입력</button>
<div>...<div>
`
Insert cell
{ // 주교재 2장에 소개된 구식 이벤트 등록 방식
let button = doc02.querySelector('button')
let input = doc02.querySelector('input')
let output = doc02.querySelector('div')

button.onclick = () => { // 입력을 누르면 실행되는 메소드
let name = input.value // 검색창에 입력하는 문자열
output.innerHTML = "<b>" + name + "</b>님 잘오셨습니다!" //innerHTML로 div태그의 내용을 바꿔주는 부분
}
}
Insert cell
doc03 = html`
<h2>환영합니다</h2>
<input>
<button>입력</button>
<div>...</div>
`
Insert cell
{ // 요즘의 바람직한 방식의 이벤트 등록 (주교재 08-4의 p. 250)
const button = doc03.querySelector('button')
const input = doc03.querySelector('input')
const output = doc03.querySelector('div')
button.addEventListener(
'click',
() => {
const name = input.value
output.innerHTML = "<b>" + name + "</b>님 잘오셨습니다!"
}
)
}
Insert cell
timeString = { // js-time
const now = new Date() // Date()는 현재 시간이 now에 할당해주는 프로토타입 클래스라 생각.
const display = now.toLocaleTimeString() // toLocaleTimeString는 현재 시간을 문자열로 변환
return "현재 시각은 " + display
}
Insert cell
Insert cell
input04 = html`<input>`
Insert cell
button04 = html`<button id="btn04">입력</button>`
Insert cell
output04 = html`<div>...</div>`
Insert cell
input04 // 위에 HTMLInputElement는 html문법이 아닌 자바스크립트에서 html 접급할 때 이런 프로그래밍 API를 가지고 접근을 한다. 이런식으로 자바스크립트에서 다룰 때에는 dom이라는 키워드를 통해서 mdn을 검색해라
Insert cell
button04
Insert cell
Insert cell
// html로 나타나는 셀에 이름을 붙이면 그것은 DOM객체를 참조하게 된다.
doc05 = html`
<div>
HTML 예제
<ul style="background-color: LightGray">
<li id="zero" class="even">0</li>
<li id="one" class="odd" >1</li>
<li id="two" class="even">2</li>
<li id="three" class="odd" >3</li>
<li id="four" class="even">4</li>
<li id="five" class="odd" >5</li>
</ul>
</div>
`
Insert cell
{
//return doc05;

// 위 HTML 예제 안의 모든 li 요소를 검은 바탕에 흰글씨로
let all = doc05.querySelectorAll('li'); //querySelectorAll는 인자를 여러 개 선택할 수 있음.
all.forEach( e => { // e는 li를 인자로 받음
e.style.color = 'white'; // li의 글씨를 흰색으로 바꿔라
e.style.backgroundColor = 'black'; // ul의 배경색을 검정으로 바꿔라
} );

//return doc05;
// DOM API를 이용해 선택자로 골라낸 요소(element) 하나의 글자색과 배경색 변경
let e = doc05.querySelector('.even'); // 다른 선택자로도 해보라
//querySelector는 요소를 하나만 선택하기 때문에 even이 가장 첫번째 쓰여 있는 '0'에만 적용됨.
// 하나의 element 스타일 변경
e.style.color = 'red';
e.style.backgroundColor = 'yellow'

//return doc05;
// DOM API를 이용해 선택자로 골라낸 요소(element) 여러개의 글자색과 배경색 변경
let es = doc05.querySelectorAll('.even'); // 다른 선택자로도 해보라
//querySelectorAll의 인자는 요소를 여러개 선택하여 한번에 여러 개의 요소를 변경할 때 사용됨.
// element 여러개 스타일 변경
for (let i = 0; i < es.length; ++i) {
es[i].style.color = 'red';
es[i].style.backgroundColor = 'yellow';
}

return doc05;
}
Insert cell
Insert cell
now = new Date()
Insert cell
// ObservableHQ에서도 vscode 정도까진 아니라도 어느 정도의 인텔리센스(자동완성) 기능 지원됨
// now. 입력하고 탭을 눌러보라
// now.
Insert cell
function calcKoreanAge(birthYear) {
const now = new Date()
const currentYear = now.getFullYear()
const age = currentYear - birthYear + 1
return age
}
Insert cell
calcKoreanAge(1997)
Insert cell
calcKoAge = function (birthYear) { //function다음에 함수이름을 안주면 이름없는 함수식가 된다. 즉 함수 내용이 되는 것이다. 함수 대상을 calcKoAge에 저장함. 여기서 굳이 function을 써줘야하나 해서 중간에 =>만 쓸 수 있게 한 것이다.
const now = new Date()
const currentYear = now.getFullYear()
const age = currentYear - birthYear + 1
return age // Es5버전
}
Insert cell
calcKoAge(1990)
Insert cell
calcKorAge = birthYear => new Date().getFullYear() - birthYear + 1 //Es6에서 지원하는 화살표함수 문법
/*calcKorAge = (birthYear) => {
return new Date().getFullYear() - birthYear + 1 }//와 같음
//return이 한줄인 함수이거나 (인자)가 하나이면 return과 괄호를 생략가능하다.*/
Insert cell
calcKorAge(1998)
Insert cell
{
const x = 10 // 변수를 재정의 할 수 없음
// ...
x = x + 2
return x
}
Insert cell
{
let x = 10 // 변수를 재정의 할 수 있음
// ...
x = x + 2
return x
}
Insert cell
Insert cell
// typeof 1990 // 숫자는 실수 정수 구분하지 않고 number 타입이다.
Insert cell
// typeof 3.141592
Insert cell
// typeof "hello" // javaScript에서는 " '는 같은 기능을 하므로 모두 string 타입이다.
Insert cell
// typeof 'hello'
Insert cell
// typeof 'h'
Insert cell
// typeof true
Insert cell
// typeof false
Insert cell
// typeof (1 < 2)
Insert cell
// typeof calcKorAge
Insert cell
md`null과 undefined에 대해 ... 다음에 대면강의 때 정리`
Insert cell
{
const first // 초기화 안해주면 에러 const first = 1 이런식으로 작성해야 오류 안남
}
Insert cell
{
let first // 초기화 안해주면 undefined
return first
}
Insert cell
{
let second = 100
// .. 뭔가 열심히 second를 사용하다
second += 1
// 더 이상 second를 사용하지 않겠다 또는 정상적인 값이 지정되어 있지 않다는 것을 명확히 해 주고 싶을 때
second = null
return second
}
Insert cell
Insert cell
seasons = ["봄", "여름", "가을", "겨울"]
Insert cell
typeof seasons // 복잡한 것을 거의 object 타입으로 나옴. 구체적으로 알기 위해서는 instanceof 사용
Insert cell
seasons instanceof Object // 구체적으로 타입을 알기 위해서는 instanceof 사용
Insert cell
seasons instanceof Array // 구체적으로 Array를 알아보기 위해 사용
Insert cell
seasons instanceof Node
Insert cell
//seasons. 하고 탭을 쳐서 어떤 메소드들이 있나 보자
Insert cell
Insert cell
kim = ( { givenName: "John", familyName: "Kim", birthYear: 1985, address: "Daejeon" } )
Insert cell
kim.address
Insert cell
kim.givenName + " " + kim.familyName + " (" + kim.birthYear + ")" + " lives in " + kim.address + "."
Insert cell
`${kim.givenName} ${kim.familyName} (${kim.birthYear}) lives in ${kim.address}` // 템플릿 리터럴
Insert cell
Insert cell
Insert cell
Insert cell
10 + 10 // number 끼리 덧셈
Insert cell
"Hello" + "World" // string 끼리 연결
Insert cell
10 + "World" // number와 string를 +하는 경우는 number를 string으로 바꿔서 연결
// 정수형과 문자열을 더하면 원래는 에러가 나야 정상이지만, js에서는 10을 문자열로 바꾸고 에러없이 10World가 출력된다. js의 문제점이다.
Insert cell
"Hello" + 10 // string과 number를 +하는 경우는 number를 string으로 바꿔서 연결
Insert cell
Insert cell
10 == "10"
Insert cell
10 === "10"
Insert cell
["봄", "여름"] == ["봄", "여름"]
// Object 끼리는 같을 것 같지만, Object 끼리는 == 연산이 === 연산과 같이 동작
Insert cell
["봄", "여름"] === ["봄", "여름"]
Insert cell
{
const arr1 = ["봄", "여름"]
const arr2 = arr1 // 같은 객체로 초기화
return arr1 === arr2
}
Insert cell
{
const arr1 = ["봄", "여름"]
const arr2 = ["봄", "여름"] // 같은 내용의 배열이지만 별도의 객체로 초기화
return arr1 === arr2
}
Insert cell
Insert cell
{ // if else 예제
let userNumber = 123
if (userNumber % 3 == 0) {
return "3의 배수입니다."
} else {
return "3의 배수가 아닙니다."
}
}
Insert cell
doc06 = html`<div>...</div>`
Insert cell
{ // switch 예제 1-마케팅, 2-개발, 3-디자인
let session = 1
switch(session) {
case 1: doc06.innerHTML = "마케팅 세션은 201호에서 진행됩니다."
break;
case 2: doc06.innerHTML = "개발 세션은 202호에서 진행됩니다."
break;
case 3: doc06.innerHTML = "디자인 세션은 203호에서 진행됩니다."
break;
default: doc06.innerHTML = "잘못 입력했습니다."
}
}
Insert cell
Insert cell
{ // 1에서 100까지 덧셈
let sum = 0
for (let i = 1; i <= 100; ++i) {
sum += i
}
return sum
}
Insert cell
{ // 1에서 100까지 덧셈
let sum = 0
let i = 1
while (i <= 100) {
sum += i
++i
}
return sum
}
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