쌍용교육센터 - 35일

개발자가 되고 싶어요 ㅣ 2024. 4. 5. 19:01

2024.04.05

배열 요소의 정렬

<script type="text/javascript">
	const array = ['가','하','아','나'];
	//배열 요소의 목록
	document.write(array + '<br>');
	
	array.sort();//오름차순 정렬
	document.write(array + '<br>');
	
	array.reverse();//반대로 정렬
	document.write(array + '<br>');
	document.write('-------------<br>');
	
	const array2 = [52,273,103,32]
	document.write(array2 + '<br>');
	
	array2.sort(function(left,right){
		return left - right;
	});//오름차순 정렬
	document.write(array2 + '<br>');
	
	array2.sort(function(left,right){
		return right - left;
	});//내림차순 정렬
	document.write(array2 + '<br>');
	
</script>

 

배열의 메서드 사용

<script type="text/javascript">
	const array = ['파도','하늘','도시','구름'];
	//배열 요소의 목록 출력
	document.write(array + '<br>');
	
	//join() : 배열의 요소 전체를 쉼표를 구분자로 반환
	document.write('array.join() : ' + array.join() + '<br>');
	document.write('array.join("-") : ' + array.join('-') + '<br>');
	
	//slice() : 지정한 인덱스 범위의 데이터를 추출해서 배열로 반환
	//지정한 인덱스부터 마지막 인덱스까지의 데이터를 추출해서 배열로 반환
	document.write('array.slice(2) : ' + array.slice(2) + '<br>');
	//시작 인덱스부터 끝 인덱스전까지
	document.write('array.slice(1,3) : ' + array.slice(1,3) + '<br>');
	
	//concat() : 전달한 인자를 이용해서 새로운 배열 생성 반환
	//문자열을 인자로 전달해서 새로운 배열 반환
	document.write('array.concat("서울","부산") : ' + array.concat('서울','부산') + '<br>');
	//배열을 인자로 전달해서 새로운 배열 반환
	document.write('array.concat(["한국","미국"] : ' + array.concat(['한국','미국']));
</script>

 

 

메서드를 이용한 배열의 요소 삽입/삭제

<script type="text/javascript">
/*
push() : 배열 객체 마지막에 새 데이터를 삽입
pop() : 배열에 저장된 데이터 중 마지막 인덱스에 저장된 데이터를 삭제
shift() : 배열 객체에 저장된 데이터 중 첫 번째 인덱스에 저장된 데이터를 삭제
unshift() : 배열 객체의 가장 앞의 인덱스에 새 데이터를 삽입
 */
	const array = [];
	array.push(10,20,30);//삽입
	//배열 요소의 목록 출력
	document.write(array + '<br>');
	
	array.push(40);//삽입
	document.write(array + '<br>');
	document.write('---------<br>');
	
	//배열의 시작에 새 값을 추가
	array.unshift('melon');
	document.write(array + '<br>');
	document.write('---------<br>');
	
	array.pop();//배열의 마지막 요소를 삭제
	document.write(array + '<br>');
	array.pop();//배열의 마지막 요소를 삭제
	document.write(array + '<br>');
	document.write('---------<br>');
	
	//배열의 시작에서 값 하나를 제거
	array.shift();
	document.write(array);
	
</script>

 

indexOf

<script type="text/javascript">
	const array = [10,20,30,40,50,50,40,30,20,10];
	             // 0  1 2  3  4  5  6  7  8  9
	
	//요소를 인자로 전달하면 해당 요소의 인덱스 반환
	let output1 = array.indexOf(40);
	document.write(output1 + '<br>');
	let output2 = array.indexOf(80);
	document.write(output2 + '<br>');
	let output3 = array.lastIndexOf(40);
	document.write(output3 + '<br>');
	let output4 = array.lastIndexOf(80);
	document.write(output4);
</script>

 

forEach

<script type="text/javascript">
	const array = [1,2,3,4,5,6,7,8,9,10];
	
	let sum = 0;
	//배열의 요소에 접근해서 반복 처리할 수 있는 메서드
	array.forEach(function(element,index,array){
		//element : 배열에 저장된 요소
		//index : 요소의 인덱스
		//array : 사용 중인 배열 객체
		
		//배열 요소의 총합
		sum += element;
	
		document.write(index + ':' + element + '->' + sum + '<br>');
		document.write('배열 객체 : ' + array + '<br>');
	});
	document.write('--------------------<br>');
	document.write('배열 요소의 합계 : ' + sum);
</script>

 

filter

<script type="text/javascript">
	//filter() : 특정 조건을 만족하는 새로운 배열을 만들 때 사용
	const array = [1,2,3,4,5,6,7,8,9,10];
	
	//5이하의 데이터를 새로운 배열에 담아서 반환
	const new_array = array.filter(function(element,index,array){
				 //조건	
		return element <= 5;
	});
	
	document.write(new_array);
</script>

 

map

<script type="text/javascript">
	//map() : 값을 새롭게 정의한 후 새로운 배열을 만들어 반환
	const array=[1,2,3,4,5,6,7,8,9,10];
	
	//요소*요소 값이 저장된 배열 반환
	const new_array = array.map(function(element,index,array){
		          //계산식
		return element * element;
	});
	
	document.write(new_array);
	
</script>

 

객체

<script type="text/javascript">
	//객체 생성
	const product = {
			//속성(key(프로퍼티):value)
			제품명:'캐스피',
			제품번호:'A1001',
			기능:'Hi Speed',
			원산지:'대한민국',
			가격:1000,
			업데이트지원:true
	};
	//객체의 속성 호출
	document.write(product.제품명);
	document.write('<br>');
	document.write(product.가격);
	document.write('<br>');
	
	document.write(product['업데이트지원']);
	document.write('<br>');
	document.write(product['기능']);
	document.write('<br>--------------<br>');
	
	const country = {
			'행정 수도':'서울',
			'인구수~':10000
	};
	document.write(country['행정 수도']);
	document.write('<br>');
	document.write(country['인구수~']);
	
</script>

 

for in 반복문

<script type="text/javascript">
	const product = {
			name:'eclipse',
			price:'10,000원',
			language:'한국어',
			supportOS:'win10',
			subscription:true
	};
	//for in 반복문
	for(let key in product){
		document.write(key + ':' + product[key] + '<br>');
	}
	
</script>

 

객체 속성과 메서드

<script type="text/javascript">
	let name = '장영실';
	//객체 생성
	const person = {
			//속성 지정
			name:'홍길동',
			//메서드 지정
			eat:function(food){
				let name = '이순신';
				/*
				this : 메서드 내에서 자기자신이 가지고 있는 속성(또는 메서드)를
				호출하고 싶을 때 객체 내부에서 객체를 참조한다는 의미 this 사용
				
				this.name 형식으로 속성 호출
				this.name이 아니라 name을 호출하면 메서드 내에 선언한 지역변수
				를 찾고 없을 경우 객체 밖에 선언된 변수를 찾음
				*/
				document.write(name + '이 ' + food +'을 먹습니다.');
			}
	};
	//객체의 속성 호출
	document.write(person.name + '<br>');
	//객체의 메서드 호출
	person.eat('밥');
</script>

 

객체에 메서드 추가

<script type="text/javascript">
	const student = {};
	
	//객체에 속성 추가
	student.이름 = '홍길동';
	student.취미 = '악기';
	student.특기 = '프로그래밍';
	student.장래희망 = '프로그래머';
	
	//in 키워드를 이용해서 객체 내의 속성 존재 여부 체크
	document.write(('특기' in student) + '<br>');
	document.write(student.이름 + '<br>');
	document.write(student.취미 + '<br>');
	document.write('------------<br>');
	
	//객체에 메서드 추가
	student.play = function(){
		document.write('피아노를 연주하다');
	};
	
	//생성한 메서드 호출
	student.play();
	document.write('<br>---------------<br>');
	
	//for in 반복문을 이용해서 객체의 속성과 메서드 출력
	for(let key in student){
		document.write(key + ':' + student[key] + '<br>');
	}
</script>

 

객체 메서드

<script type="text/javascript">
	//ES6부터 function 키워드를 생략한 축약 표현을 사용 가능
	//객체 생성
	const obj = {
			//속성 지정
			name:'Peter',
			//메서드 지정
			play:function(){
				document.write('열심히 일하다');
			},
			//메서드 축약 표현
			sayHi(){
				document.write('Hi! ' + this.name);
			}
	};
	//객체의 메서드 호출
	obj.sayHi();
</script>

 

생성자 함수 정의

<script type="text/javascript">
	//생성자 함수 정의
	function Animal(name,age){
		//속성 지정
		this.name = name;
		this.age = age;
		//메서드
		this.eat = function(){
			document.write('맛있는 먹이를 먹습니다.');
		}
	}
	//객체 생성
	const animal = new Animal('비둘기',10);
	//속성 호출
	document.write(animal.name + '<br>');
	document.write(animal.age + '<br>');
	//메서드 호출
	animal.eat();
	
</script>

 

생성자 함수 사용

<script type="text/javascript">
	//생성자 함수 정의
	function Student(name,korean,math,english,science){
		//속성 지정
		this.name = name;
		this.korean = korean;
		this.math = math;
		this.english = english;
		this.science = science;
		//메서드 지정
		this.getSum = function(){
			return this.korean + this.math 
			             + this.english + this.science;
		};
		this.getAverage = function(){
			return this.getSum() / 4;
		};
		this.toString = function(){
			return this.name + ', ' + this.getSum() + ',' 
			          + this.getAverage();
		};
	}
	//생성자 함수를 이용한 객체 생성
	const student = new Student('홍길동',99,98,97,99);
	document.write(student + '<br>');
	
	
</script>

 

프로토타입

<script type="text/javascript">
	//생성자 함수 정의
	function Student(name,korean,math,english,science){
		//속성 지정
		this.name = name;
		this.korean = korean;
		this.math = math;
		this.english = english;
		this.science = science;
	}
	//프로토타입은 생성자 함수를 사용해 생성된 객체가 공통으로 가지는 공간
	Student.prototype.getSum = function(){
		return this.korean + this.math + this.english 
		                   + this.science;
	};
	Student.prototype.getAverage = function(){
		return this.getSum() / 4;
	};
	Student.prototype.toString = function(){
		return this.name + ', ' + this.getSum() + ', '
		                 + this.getAverage();
	};
	
	//배열 생성
	const students = [];
	//배열에 객체 저장
	students.push(new Student('홍길동',99,98,97,99));
	students.push(new Student('박문수',98,98,97,99));
	students.push(new Student('장영실',97,98,97,99));
	students.push(new Student('강호동',96,98,97,99));
	students.push(new Student('유재석',95,98,97,99));
	
	//출력
	document.write('이름, 총점, 평균<br>');
	for(let i in students){
		document.write(students[i].toString() + '<br>');
	}
	
</script>

 

상속

<script type="text/javascript">
	//자바스크립트는 프로토타입을 이용해서 상속 구현
	function Human(age){
		this.age = age;
	}
	Human.prototype.type = '사람';
	Human.prototype.getType = function(){
		return this.type;
	};
	Human.prototype.getAge = function(){
		return this.age;
	};
	
	const human = new Human(20);
	document.write('human.type = ' + human.type + '<br>');
	document.write('human.age = ' + human.age + '<br>');
	document.write('human.getType() = ' 
			                  + human.getType() + '<br>');
	document.write('human.getAge() = ' 
			                  + human.getAge() + '<br>');
	document.write('-------------------<br>');
	
	//자식 생성자 함수 정의
	function Student(age){
		this.age = age;
	}
	Student.prototype = Human.prototype;
	//프로토타입의 생성자를 재정의(정의하지 않아도 구동상의 문제는 없음)
	Student.prototype.constructor = Student;
	
	//Human를 상속받은 Student 객체 생성
	const student = new Student(40);
	document.write('student.type = ' + student.type + '<br>');
	document.write('student.age = ' + student.age + '<br>');
	document.write('student.getType() = ' 
			                  + student.getType() + '<br>');
	document.write('student.getAge() = ' 
			                  + student.getAge() + '<br>');
	
</script>

 

instanceof

<script type="text/javascript">
	//생성자 함수 정의
	function Student(name){
		this.name = name;
	}
	//객체 생성
	let student = new Student('홍길동');
	
	//해당 객체가 어떤 함수를 통해 생성됐는지 확인할 때 instanceof 키워드를
	//사용. 객체가 속한 클래스와 상위 클래스 체크
	document.write(student instanceof Student);//true
	document.write('<br>');
	document.write(student instanceof Object);//true
	document.write('<br>');
	document.write(student instanceof Number);//false
</script>

 

클래스

<script type="text/javascript">
    //클래스 정의
	class Person{
		//클래스 필드
		name = 'Smith';
		//메서드
		getName = function(){
			return this.name;
		};
	}
	//객체 생성
	const me = new Person();
	document.write(me);
	document.write('<br>');
	
	document.write(me.name);
	document.write('<br>');
	
	document.write(me.getName());
	
</script>

 

클래스와 상속

<script type="text/javascript">
	//부모 클래스 정의
	class Animal{
		//생성자
		constructor(age,weight){
			this.age = age;
			this.weight = weight;
		}
		//메서드
		eat(){
			return "eat";
		}
		move(){
			return "move";
		}
	}
	
	//자식 클래스 정의(부모 클래스를 자식 클래스에 상속)
	class Bird extends Animal{
		fly(){
			return 'fly';
		}
	}
	
	//자식 클래스 객체 생성
	const bird = new Bird(1,5);
	document.write(bird.age + '<br>');
	document.write(bird.weight + '<br>');
	document.write(bird.eat() + '<br>');
	document.write(bird.move() + '<br>');
	document.write(bird.fly());
	
</script>

'IT 국비 교육' 카테고리의 다른 글

쌍용교육센터 - 37일  (0) 2024.04.09
쌍용교육센터 - 36일  (0) 2024.04.08
쌍용교육센터 - 34일  (0) 2024.04.04
쌍용교육센터 - 33일  (1) 2024.04.03
쌍용교육센터 - 32일  (0) 2024.04.02