*** javascript
* 배열
1. 선언
- 값과 크기가 정해져있지 않을 때
var str=new Array();
var str[0]= 70; str[1]=80; str[2]=90;
- 값과 크기가 정해져있을 때
var str=new Array(70,80,90);
var str=[70,80,90];
+) 배열 var num=['사당','교대','방배','강남',10,20,30]; 일 때
typeof(num)=object (데이터형이 객체)
typeof(num[0])=string
typeof(num[4])=number
2. 속성
- .length: 배열의 크기를 설정 (ex. for(var i=0; i<a1.length; i++))
3. 메소드1
(var num=['사당','교대','방배','강남',10,20,30];)
- join(): 괄호 안의 문자로 배열 값을 연결해 나열하고 그걸 하나의 문자열로 결합
document.write(num.join('-')); ---> 출력: 사당-교대-방배-강남-10-20-30
document.write(num.join('&')); ---> 출력: 사당&교대&방배&강남&10&20&30
+) typeof(num.join('-')) --> string num.join('-').length --> 20
- reverse(): 배열 값의 출력 순서를 반대로 바꿔주는 함수 (일회성, 배열에 변화 없음)
document.write(num.reverse()); ---> 출력: 30,20,10,강남,방배,교대,사당
-★ sort(): 배열 값을 오름차순(작->큰, ㄱ->ㅎ) 정렬해 출력 (영구적, 배열 내부를 순서대로 정렬해 저장하는 것)
document.write(num.sort()); ---> 출력: 10,20,30,강남,교대,방배,사당
+) 내림차순 정렬 (sort로 오름차순 정렬 후 reverse로 반대로 출력)
document.write(num.sort().reverse()); ---> 출력: 사당,방배,교대,강남,30,20,10
(var greenLine=['사당','교대','방배','강남'];)
(var yellowLine=['미금','정자','모란','수서'];)
(var blueLine=['안양','용산','서울','종각'];)
-★ slice(start index, end index): start index부터 배열 값을 (end-1)개만큼 추출
document.write(greenLine.slice(0, 3)); ---> 사당,교대,방배 (greenLine[0]부터 [(3-1)]까지)
- concat(): n개의 배열을 하나로 결합 (일회성, 배열에 변화 없음)
document.write(greenLine.concat(yellowLine, blueLine)); ---> 사당,교대,방배,강남,미금,정자,모란,수서,안양,용산,서울,종각
- pop(): 배열의 가장 마지막 요소 값을 삭제
greenLine.pop(); //강남 삭제
greenLine.pop(); //방배 삭제
document.write(greenLine+"<br>"); ---> 출력: 사당,교대
- push(): 배열의 끝에 새 요소를 추가한 후 리턴
greenLine.push('삼성','당산'); //배열 끝에 차례대로 데이터 추가됨
document.write(greenLine+"<br>"); ---> 출력: 사당,교대,삼성,당산
- shift(): 배열의 첫 번째 요소 값을 삭제
greenLine.shift(); //사당 삭제
greenLine.shift(); //교대 삭제
document.write(greenLine+"<br>"); ---> 출력: 삼성, 당산
- unshift(): 배열의 처음에 새 요소를 추가한 후 리턴
greenLine.unshift('신촌','합정'); //배열 처음에 차례대로 데이터 추가됨
document.write(greenLine+"<br>"); ---> 출력: 신촌, 합정, 삼성, 당산
* String (문자열, 내장객체)
1. 선언
- var str1= new String("It's a Javascript Example.");
- var str2='wow! It's a Javascript!'; -- 따옴표(' ', " ") 사용
+) typeof(str1)=string
2. 속성
- length: 문자열 길이 (ex. document.write(str1.length);)
3. 메소드
(var t="hello javascript day? have a nice day!";)
- charAt(): 특정 index의 문자를 추출, 없다면 공백
document.write(t.charAt(10)); ---> 출력: s (index는 0부터 시작하므로 10 -> 11번째 문자)
- indexOf(): 앞에서부터 검색해 해당되는 문자의 index 번호를 추출, 없다면 -1 리턴
document.write(t.indexOf('day')); ---> 출력: 17 (첫 day가 18번째에 있으므로)
+) 특정 index 번호부터 검색★
document.write(t.indexOf('day',18)); //index 18번 이후부터 검색 ---> 출력: 34 (두번째 day 검색됨)
- lastIndexOf(): 뒤에서부터 검색해 해당되는 문자의 index 번호를 추출, 없다면 -1 리턴
document.write(t.lastIndexOf('day')); ---> 출력: 34
document.write(t.lastIndexOf('day',18)); ---> 출력: 17
- match(): 검색하려는 문자가 존재한다면 그 문자를 추출해 리턴, 없다면 null 리턴
document.write(t.match('day')+"<br>"); ---> 출력: day
document.write(t.match('no')+"<br>"); ---> 출력: null
- toLowerCase(): 문자열을 소문자로 변환
- toUpperCase(): 문자열을 대문자로 변환
- substring(index): index부터 끝까지 추출 (= slice()와 같은 기능)
substring(start index, end index): start index부터 (end-1) index까지 문자 추출
document.write(t.substring(6, 20)); ---> 출력: javascript day (6부터 19까지 '14개' 추출)
- substr(index): index부터 끝까지 추출
★substring(start index, number): start index부터 number개만큼 문자 추출 (!substring과의 차이점!)
document.write(t.substr(6, 20)); ---> 출력: javascript day? have (6부터 '20개' 추출)
- ★split("구분기호"): 기호(공백도 가능)를 기준으로 문자를 분리 -> 배열로 리턴.
var s1=t.split(" ") //공백 기준으로 문자 나눠 s1 배열로 저장
for(var i=0; i<s1.length; i++){
document.write(s1[i]+" ");
} ---> 출력: hello javascript day? have a nice day! (공백 기준으로 문자가 분리되어있음)
4. 예시
- 사용자가 입력한 문자를 대문자로 변환 -> toUpperCase()
var name=prompt("영어 문자 입력");
var pname=name.toUpperCase();
document.write(pname+"<br>")
- 주민번호 뒷자리를 *로 출력
var num=prompt("주민번호 입력","000000-0000000");
// 1. split() 사용
var pnum1=num.split("-");
document.write(pnum1[0]+"-*******"+"<br>");
// 2. substring() 사용
var pnum2=num.substring(0,7); //0부터 index 6까지 총 7개 추출
document.write(pnum2+"*******"+"<br>"); //-까지 추출했으니 -은 안 써도 됨
// 3. substr() 사용
var pnum3=num.subst(0,7); //0부터 문자 7개 추출
document.write(pnum2+"*******"+"<br>"); //위와 같음
* Math (연산, 내장객체)
: 생성자가 존재하지 않음 -> new 연산자로 선언할 필요 없이 그냥 Math.속성(메소드)로 사용하면 됨
1. 속성
- E (오일러 상수) - PI (원주율) - etc.
2. 메소드
- sin(x),cos(x),tan(x): 삼각함수 값 (x=radian)
- max(x,y), min(x,y)
- abs(x): 절대값
document.write(Math.abs(-2.5234)); ---> 출력: 2.5234
- round(x): 반올림
document.write(Math.round(2.5234)); ---> 출력: 3
- ceil(x): 올림
document.write(Math.ceil(2.4234)); ---> 출력: 3
- floor(x): 내림
document.write(Math.floor(2.5234)); ---> 출력:2
- exp(x): 자연로그의 지수 값 반환 (exp(x)=e^x)
- log(x): 자연로그 값 반환 (log(x)=ln x)
- sqrt(x): 제곱근 값 반환 (x=sqrt(x)^2)
- pow(x,y): 거듭제곱 값 반환 (pow(x,y)=x^y)
- random(): 0~1 사이 난수 반환
* 이벤트
1. 처리 방식
01. inline 방식 : 태그 내에 직접 입력 (ex. <input type='button' value='호출' onClick="check()"> )
02. property 방식 : 객체의 속성에 이벤트를 등록
<input type="button" id="btn" value="확인">
<script>
var btn = document.getElementById('btn'); //id='btn'인 요소를 찾아 그 객체를 변수 btn에 반환
---> 즉 변수 btn에 <input type="button" id="btn" value="확인"> 의 속성이 들어가 있는 상태
btn.onclick = function(){ //이벤트 타겟 객체 속성(var btn)에 이벤트 핸들러(onClick)를 연결
alert('Hello world'); //발생할 function()을 만들어 핸들러를 이용해 변수 btn과 엮어버린 것
}
</script>
---> 위치는 <head>여도 되고 <body>여도 되지만... 보통 함수 선언은 head에서 많이 함
- document.getElementById('id') : 문자열 ('')과 일치하는 id 속성을 가진 요소를 찾아 이를 나타내는 객체를 반환
+) (element : 모든 객체가 상속하는 범용적인 기반 클래스)
03. 표준 이벤트 모델 방식(DOM Level 2 방식) : 한 객체에 다수의 이벤트를 등록
---> 표준방식 브라우저/비표준방식 브라우저로 나눠 각각 동작할 수 있도록 if~else if문 사용해야 함
var btn = document.getElementById('btn'); //id='btn'인 객체 검색해 속성을 변수 btn에 반환시킴
if(btn.addEventListener){ // 표준 방식 브라우저(크롬,파이어폭스,사파리 등)
이벤트 대상. addEventListener('이벤트명', 호출할 함수명);
btn.addEventListener('click', btnEvent1);
} else if(btn.attachEvent){ // 비표준 방식브라우저(IE8 이하)
이벤트 대상. attachEvent('on'+'이벤트명', 호출할 함수명);
btn.attachEvent('onclick', btnEvent1);
}
- addEventListener(): EventTarget 인터페이스의 메소드. 지정한 이벤트가 발생할 때마다 호출할 함수를 지정
- attachEvent(): IE8 이하 및 오페라 브라우저에서 열릴 때? 비표준방식 브라우저일 때 이걸 사용
* window 객체 : 내장 객체 중 가장 상위 객체 - 보통 생략해서 사용함
1. 속성
status : 브라우저 상태선에 나타날 문자열
opener : open()메소드를 연 문서가 있는 윈도우
2. 메소드
01. window.open("팝업창에서 실행될 문서명","윈도우 이름","옵션");
---> 옵션에서 높이, 너비는 반드시! 설정! 필수! 만약 등록하지 않으면 문서가 새 탭으로 열리게 되는듯
window.open("http://naver.com","MyWin01","width=400, height=300, left=100, top=100");
window.open("http://google.com","MyWon02","width=400, height=300, left=500, top=100");
- 옵션 종류
- width, heigth : 팝업창 너비, 높이
- left, top : 팝업창 위치
02. window.close();
---> 팝업창을 닫고 싶다면 정확히 그 팝업에 대한 close()라고 명시해줘야함
var w1=window.open("date01.html","Mywin","width=200, height=200, left=100, top=100");
w1.close(); //w1에 대한 close()임을 명시
* document 객체 : <body>태그 안의 내용들과 직접적으로 연결되어있음. 툴바, 상태선, 문서위치 정보에 접근 불가능
* 페이지 이동
1. meta 태그 이용
---> 특징: 시간 설정(제어) 가능
<meta http-equiv="refresh" content="3; url=http://naver.com">
//meta 태그는 보통 head에... 3초 후에 url로 이동한다는 의미 (content)
2. location 객체 : 열려있는 윈도우의 url 주소에 관한 정보를 제공. 주로 부라우저 상단의 위치 필드 값을 가짐
---> 특징: 페이지 이동 시 메시지 출력 가능
'수업 > 정리' 카테고리의 다른 글
220221 폼 유효성 검사, 쿠키, jquery (0) | 2022.02.21 |
---|---|
220218 document location history navigator form_ (0) | 2022.02.18 |
220216 javascript event, function, date (0) | 2022.02.16 |
220215 bootstrap , Javascript 출력, 연산자 (0) | 2022.02.15 |
220214 CSS_레이아웃, 배치 , 반응형 웹 , bootstrap (0) | 2022.02.14 |