WEB/javascript

01. javascript 기본 변수 정의

slow333 2023. 1. 27. 20:56

변수는 const(상수), let(변수 중복 허용안함), var 이 있음

일반적으로 let을 사용, 가능하면 const를 사용할 것을 권장

 

java와 달리 반환값 지정이 없으며 대부분의 함수에서 lambda 형태의 익명 함수를 많이 사용(웹 특성)

for문, while문 과 lambda는 사용 방식이 java와 유사

<h1>Loop</h1>
<script>
  document.write('<li>1</li>');
  let count = 0;
  while (count < 3) {
    document.write('<li>2</li>');
    count ++;
  }
  document.write('<li>4</li>');
</script>

document.write(); ==> 내부에 html tag를 정의 할 수있고, 변수를 받을 수도 있음

<h1>Loop & Array</h1>
<script>
  const names = ['kim', 'lee', 'choi', 'pak'];
  for (let i = 0; i < names.length; i++) {
    document.write(names[i]+'<br>');
  }
  document.write('===========for==========='+'<br>');
  for (let i of names) {
    document.write(i+'<br>');
  }
  document.write('===========forEach========'+'<br>');
  names.forEach(function (name, index, array) {
    document.write(name+'<br>')
  });
  document.write('=====인텍스 까지 출력 ======'+'<br>');

  names.forEach(function (name, index, array) {
    document.write(name, index+'<br>')
  });
  document.write('=======각각을 배열에 담음======'+'<br>');

  names.forEach(function (name, index, array) {
    document.write(name, index, array+'<br>')
  });
  document.write('===이게 가장 심플, 람다 함수===='+'<br>');
  names.forEach((name) => document.write(name+'<br>'))
</script>

html 내부에서 사용되는 tag에 대한 검색을 위해서

document.querySelector("tag 이름');   ==> 1개만 찾음

document.querySelectorAll("tag 이름'); ==> 모두 찾음(list 형태로 반환)

onclick event에 대한 action을 정의한 예제

<body style="background-color: white ; color: black;">
<h1><a href="index.html">WEB</a> </h1>
<input type="button" value="night" id="night_day" onclick="
  let target = document.querySelector('body');
  let links = document.querySelectorAll('a');

  if(this.value === 'night'){
    target.style.backgroundColor = 'black';
    target.style.color = 'white';
    this.value = 'day';
    for( l of links){
      l.style.color='powderblue';
    }
  } else {
    target.style.backgroundColor = 'white';
    target.style.color = 'black';
    this.value = 'night';
    for( l of links){
      l.style.color='blue';
    }
  }">
<ol>
  <li>  <a href="doc/html.html">HTML</a> </li>
  <li>  <a href="doc/css.html">CSS</a> </li>
  <li>  <a href="doc/js.html">Javascript</a> </li>
</ol>

<h2>JavaScript</h2>
<div>
  자바스크립트(영어: JavaScript)는 객체 ...
</div>

</body>

이를 함수를 사용해서 정의하면

nightAndDay.js 를 생성하고 함수를 정의 이름은 적당히

함수의 매개 변수로 self를 정의하고, 기존의 this를 무두 self로 변경

   -  html에서는 이를 this로 받아서 사용

      ==> this가 함수의 매개변수로 등록되고 함수 내부에서는 self로 받아서 사용

  * 매개변수 지정을 안하면 일반적으로 this는 전체 객체의 전역 변수로 동작하여 자기 자신의 value 값을 지정하지 못하는 문제가 뱔생

function nightAndDay(self) { // 매개변수 지정
  let target = document.querySelector('body');
  let links = document.querySelectorAll('a');

  if(self.value === 'night'){
    target.style.backgroundColor = 'black';
    target.style.color = 'white';
    self.value = 'day'; // 변경
    for( l of links){
      l.style.color='powderblue';
    }
  } else {
    target.style.backgroundColor = 'white';
    target.style.color = 'black';
    self.value = 'night'; // 변경
    for( l of links){
      l.style.color='blue';
    }
  }
}

html 내부에서 javascript 파일의 경로를 지정하고, 함수를 호출하여 사용

<body style="background-color: white ; color: black;">
<h1><a href="index.html">WEB</a> </h1>
<input type="button" value="night" id="night_day" onclick="nightAndDay(this)"> // js 파일에 있는 함수를 호출
<ol>
  <li>  <a href="doc/html.html">HTML</a> </li>
  <li>  <a href="doc/css.html">CSS</a> </li>
  <li>  <a href="doc/js.html">Javascript</a> </li>
</ol>

<h2>JavaScript</h2>
<div>
  자바스크립트(영어: JavaScript)는 객체 기반...
</div>
<script src="js/nightAndDay.js"></script> //사용할 js 파일 위치
</body>

nightAndDay.js ==> refactory

세부 함수로 분리해서 정의 : 본 예제는 필요없으나 코드가 길어지면....

function nightAndDay(self) {
  let target = document.querySelector('body');

  if(self.value === 'night'){
    setBackgroundColor('black');
    setFontColor('white');
    self.value = 'day';
    setLinkColor('powderblue');
  } else {
    setBackgroundColor('white');
    setFontColor('black');
    self.value = 'night';
    setLinkColor('blue');
  }
}

function setLinkColor(color) {
  let links = document.querySelectorAll('a');
  for( link of links){
    link.style.color= color;
  }
}

function setBackgroundColor(color) {
  document.querySelector('body').style.backgroundColor = color;
}
function setFontColor(color) {
  document.querySelector('body').style.color = color;
}

다시 객체를 사용하는 방식으로 다시 refactory

객체에 대한 개념을 잡기 위해 보는 것임... java class와 비슷한 개념 인듯

function nightAndDay(self) {
  let target = document.querySelector('body');

  if(self.value === 'night'){
    Body.setBackgroundColor('black');
    Body.setFontColor('white');
    self.value = 'day';
    Links.setLinkColor('powderblue');
  } else {
    Body.setBackgroundColor('white');
    Body.setFontColor('black');
    self.value = 'night';
    Links.setLinkColor('blue');
  }
}

let Body = {
  "setBackgroundColor": function (color) {
    document.querySelector('body').style.backgroundColor = color;
  },
  "setFontColor": function (color) {
    document.querySelector('body').style.color = color;
  },
};

let Links = {
  setLinkColor: function (color) {
    let links = document.querySelectorAll('a');
    for( let link of links){
      link.style.color= color;
    }
  },
}

전반적으로 javascript는 반환값에 대한 정확한 정의가 없고,

변수 정의 시 type을 지정할 필요가 없고,

대부분의 함수가 람다 함수 형태로 정의되고 있으며,

html tag(id, class, value 값등)에 대한 제어를 위한 함수가 많으며,

array를 다룰 때 대부분이 string 형태로 generic에 대한 필요성이 적으며,

직접 html, css를 제어하기 위한 다양한 방법이 있으며,

다소 loose한 형태의 언어...

jquery를 많이 사용함...