티스토리 뷰

javascript

javascript(1)

코딩하는 둥아 2020. 7. 2. 02:28
728x90

- <script> tag

  • 모든 자바스크립트는 <script> 태그 안에서 이루어져야 함
  • html의 head나 body 아무데나 위치할 수 있음
  • external file로 참조 가능
    • <script src="myScript.js"></script>

ex) function의 형태

function myFunction() {
  document.getElementById("demo").innerHTML = "Paragraph changed.";
}

  • document: body의 모든 elemente들을 의미함

 

- innerHTML

: HTML element에 접근하기 위한 방법

 document.getElementById

  • document.getElementById('id명').innerHTML
    • --> 해당 ID를 가진 element의 내용을 바꿀 수 있다
  • document.getElementById('id명').src = 'jpg'
    • --> id를 가진 element의 src값을 변경할 수 있다
    • src를 비롯해 모든 style 변경 (fontsize, display, color...)도 가능하다
  • document.write()
    • testing을 위한 목적, 단순 프린트
    • script태그 안에서 스크린에 출력이 되도록 할 수 있다
    • HTML이 로드되고난 후 write를 사용하면, 존재하는 모든 HTML이 사라진다!
  • window.alert() : alert창 띄워줌
  • console.log() : 검사에서 console창에 내용을 띄워줌
  • window.print() : 그 창을 프린트할 수 있게 해줌

- JavaScript Statements

: Values, Operators, Expressions, Keywords, Comments

  • 변수 선언
    • 따로 변수형은 없음 
    • var x,y,z
    • 변수의 이름 선언 시, $, _ 표시가 들어가도 유효함
      • var $ = 2;
  • 세미콜론을 기준으로 statement구분함!

- Functions

 

function name(parameter1, parameter2, parameter3,,) {

//code

}

 

  • function 호출 시, ()없이 호출하면 function의 definition이 리턴된다!
    • ex) function toCelsius(f) { return ~~~ }
  • property와 property value로 이루어진 object 변수도 존재함
    • C의 구조체와 비슷함!
    • obejectName.propertyName
    • objectName("propertyName")

 

  • =
    • assign operator
  • == / != 
    • equal to / not equal
  • === / !== 
    • equal value and eqaul type / not equal value or not equal type
  • **
    • 5 ** 2 = 25
    • x ** y = Math.pow(x,y)
    • 제곱해주기 exponentiation

 

- JavaScript Data Types

  • nubmers
  • strings
  • boolean
  • arrays
  • objects
    • name:value pairs
    • null도 object 타입
    • undefined와 null은 equal value(==)이지만 type은 (!==) 다르다
  • var x = new String() / new Number() / new Boolean() 으로 선언하면 object가 생성됨

- Common HTML Events

  • <element event="Some JavaScript">
  • onchange
  • onclick
  • onmouseover
  • onmouseout
  • onkeydown
  • onload
    • W3Schools HTML DOM Events에 더 자세한 내용이 있음!

- String Methods

  • length
  • /" : string안에 헷갈리만한 문자 넣을 때 함께 적음
  • indexOf
  • lastIndexOf
    • 없으면 return -1
  • search
    • 찾는 value의 position리턴ㅅ
  • slice(start, end) : negative 인덱스 가능
  • substring(start, end) : negative 인덱스 불가능
  • substr(start, length)
  • replace
  • toUpperCase() / toLowerCase()
  • concat()
  • trim() : removes whitespace
  • charAt(position)
  • charCondeAt(position)
  • split("str"): str을 기준으로 String을 배열로 바꿔서 저장해줌

- Number

  • string "+" int는 string으로 변환
  • +를 제외한 -,/,* 등 operator들은 string에 적용하더라도 숫자로 변화된 결과를 반환함
  • NaN : Not a Number
    • isNaN(x)
  • toString()
  • toExponential()
  • toFixed() : 소수점을 자릿수에 맞게 설정해줌
  • toPrecision() : 자릿수 숫자에서 반올림해줌
  • valueOf()
  • Number() / parseInt() / parseFloat() : 변수를 숫자로 변경해줌
  • MAX_VALUE / MIN_VALUE
  • POSITIVE_INFINITY / NEGATIVE_INFINITY / NaN

- Array

var array_name = [item1, item2, item3, ...];

var array_name = new Array {item1, item2, item3, ...} --> Bad

var array_name = []; --> Good

  • does not support arrays with named indexes
  • numbered indexes
  • Array.isArray() / isArray() / instance of
    • array_name instanceof Array --> return true of false
  • 한 Array에 다른 타입의 변수들이 들어갈 수 있음
  • array.length
  • array.forEach(Fucntion);
  • array.push : add new element
  • isArray(array)
  • array_name instanceof Array;

array는 numbered index, object는 named index!

 

- Array Method

 

- Object

var person = {firstName:"John", lastName:"Doe", age:46};

  • named indexes

- Array Methods

  • toString()
  • join() : separator 지정 가능 ex) array_name.join(" * ")
  • pop() : remove the last element, pop된 element 리턴
  • push() : 새로운 element 끝에 더함, 더해진 배열의 길이 리턴
  • shift() : 배열의 첫번째 element 삭제함, shift out된 원소의 값 반환
  • unshift() : 새로운 원소 배열 앞에 더함
  • delete array[index] : array에 hole이 생김, pop이나 shift 이용하자!
  • splice() : (추가될 인덱스, 몇개의 원소, 추가될 element), add와 delete 모두 가능
  • concat() : 배열 합치기
  • slice()
  • sort() : 알파벳 순으로 정렬해줌
    • 기본적으로 스트링
    • 숫자를 기준으로 정렬할때는 Numeric Sort!
      • Compare Function : array.sort(function(a,b){return a-b});
  • reverse() : 배열 순서 거꾸로
  • Math.max.apply / Math.min.apply : 배열에서 최댓값, 최솟값 찾아줌

- Iteration Methods

  • forEach()
    • array.forEach(myFunction); --> 배열의 각 원소에 대해 function적용
  • Array.map() : 각 원소에 function적용해 새로운 배열 생성
  • Array.filter() : 조건에 해당하는 원소만 걸러줌
  • Array.reduce() : 하나의 return value를 제공함
    • ex) 모든 배열의 합 구하기
  • Array.reduceRight()
  • Array.every() : 모든 원소가 조건을 만족했는지 반환함
  • Array.some() : 하나라도 조건을 통과했는지 반환함
  • Array.indexOf(ㅌ) / Array.lastIndexOf(x)
  • Array.find()

- Date

var D = new Date();

  • 선언하는 네가지 방법
new Date()
new Date(year, month, day, hours, minutes, seconds, milliseconds)
new Date(milliseconds)
new Date(date string)
  • toString()
  • toDateString()
    • 좀 더 읽기 쉬운 형식으로 변환해줌

 

-Date Method (get / set)

  • getTime()
  • getFullYear()
  • getMonth()
  • getDate()
  • getHours()
  • getMinutes()
  • getSeconds()
  • getMilliseconds()
  • getDay()

- Math

  • Math.PI
  • Math.round(x)
  • Math.pow()
  • Math.sqrt()
  • Math.abs(), Math.ceil(), Math.floor()
  • Math.sin(), Math.cos()
  • Math.min() / Math.max()
  • Math.random()
    • 0과 1 사이의 랜덤 숫자 리턴
    • Math.floor()와 함께 사용됨

- Booleans

  • false value
    • zero
    • -0
    • ""
    • undefined
    • null
    • Nan

- Switch Statement

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

- Java와 유사한 속성들

  • java와 동일하기 try/catch 문을 통해 error을 감지함
  • this Keyword
    • 자기 자신이 속한 object를 의미함
  • let and const
    • let: var과는 다르게 loop의 밖에서 다시 선언된 변수가 쓰일 수 없다
    • const: let과 비슷함, 다시 할당될 수 없음
      • 변수의 값을 변경할 수 없다는 뜻
  • console.log를 통한 디버깅
  • dubugger
728x90

'javascript' 카테고리의 다른 글

jquery - input 전체 체크하기  (0) 2021.01.14
jQuery - 동적으로 생성된 element에 이벤트 걸기  (0) 2020.08.01
jQuery AJAX  (0) 2020.07.31
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함