자바스크립트에서 string 은 문자라는 뜻
'Hello World'.length 라고 하면 string 프로퍼티인 length로 인해 Hello World의 글자 수가 나온다.
' 글자 ' 에서 ' ' 는 문자열로 처리를 해줌 (string)
'Hello World'.indexof(World) 처리를 하면 World라는 글자가 몇번째에 있는지 숫자로 알려준다. (6)
var name = 'KIM'; 변수 대상 지정 ( 앞의 var은 variable 의 약자 )
alert("Hi my name is "+name+"!! good") 라고 하면 alert 안의 "+name+" 으로 변수처리가 되었기에 위
name = 'KIM' 의 이름 KIM이 나온다.
<script>
document.write(1===1); 좌항 1과 우항 1을 비교연산자 ===를 이용해서 비교하고 있다. 두 항이 같으므로
</script> 출력값은 true
<script>
document.write(1===2); 해당 코드는 좌항과 우항이 다르므로 출력값은 false
</script>
해당 출력값 true 와 false를 Boolean 이라고 부름 Boolean 은 true 와 false 2개로만 이루어짐
<script>
document.write(1<2);
</script> 는 ture
<script>
document.write(1<1);
</script> 는 false
<script type="text/javascript">
document.write("1<br>");
if(true){
document.write("2<br>");
} else {
document.write("3<br>");
}
document.write("4<br>");
</script>
if 뒤에 Boolean 을 넣고 위 코드를 해석하면 1을 br 해서 만약 1이 true 값이면 2 else 3을 출력
1이 true 이므로 2를 출력하고 3은 출력 x 이후 4 출력
if 뒤가 false면 1은 true이므로 3을 출력 이후 4 출력
<input id="night-day" type="button" name="" value="night" onclick="
if(document.querySelector('#night-day').value === 'night'){
document.querySelector('body').style.backgroundColor = 'black';
document.querySelector('body').style.color = 'white';
document.querySelector('#night-day').value = 'day';
} else {
document.querySelector('body').style.backgroundColor = 'white';
document.querySelector('body').style.color = 'black';
document.querySelector('#night-day').value = 'night';
}
">
if 뒤에 넣어야하는 value 값을 찾기 위해선
document.querySelector('#night-day').value 를 사용하면 된다. (id 값이 night-day인 쿼리의 값)
검사 - 콘솔에서 해당 코드를 넣으면 value 값이 night가 뜨는 것을 알 수 있다. (검색어 javaScript Elemnetal Value)
즉, value 값이 night와 같을때 코드가 실행되게 하려면 if 뒤에
document.querySelector('#night-day').value === night 이후 value 값을 day 로 바꿔주기 위해서는
document.querySelector('#night-day').value = 'day'; 를 넣으면 된다.
리팩토링 작업 이후 <input type="button" name="" value="night" onclick=" var target = document.querySelector('body');
if(this.value === 'night'){
target.style.backgroundColor = 'black';
target.style.color = 'white';
this.value = 'day';
} else {
target.style.backgroundColor = 'white';
target.style.color = 'black';
this.value = 'night';
}
">같은 코드를 수정할때, 해당 input tag의 값 value를 칭하는 것을 this 라고 한다.document.querySelector('#night-day').value 같은 코드를 사용하면 해당 코드를 여러개 쓸때 id 값을 하나하나 바꿔야함이것을 방지하기 위해 해당 tag 를 뜻하는 this 를 넣으면 코드가 깔끔해짐. 위 button의 value 기본값이 night 이므로this.value === 'night' 이고 버튼을 누르면 this.value의 값이 day로 변한다. 라는 뜻.
var ( variable ) 변수의 값을 target으로 이름 짓고 이 변수는 = document.querySelector('body'); 라고 지정하면
target.style.backgroundColor = 'black'; 와 같이 깔끔하게 코드 정리가 가능
'JAVASCRIPT' 카테고리의 다른 글
Return 함수 (0) | 2022.09.05 |
---|---|
함수 (0) | 2022.09.05 |
22년 9월 4일 - 3 (1) | 2022.09.04 |
22년 9월 4일 - 2 (1) | 2022.09.04 |
22년 9월 3일 (0) | 2022.09.03 |