<script>
/*
object는 JavaScript에서 최상위부모객체이기 때문에 모든 객체는 Object를
상속받는다. 상속받은 모든 객체들은 Object가 가지고 있는 모든 속성과
메서드를 동일하게 사용할 수 있다. 또한 공통적으로 사용할 속성과 메서드가 있다면
Object의 prototype에 속성과 메서드를 추가하면 모든 객체에서 사용할 수 있게
된다.
JavaScript에서는 기본적으로 제공해주는 객체가 있는데 이를 통칭해서 내장객체
builtin객체라고 한다. 자주 사용하는 String, Array, Date, JSON, Math, Number...
등이 내장객체인데 이 내장객체에서는 속성과 메서드들을 제공하는데 이 속성과
메서드를 자유롭게 사용하면 보다 편리하게 프로그램을 작성할 수 있게 된다.
*/
// 1. 기본자료형은 속성이나 메서드를 가질 수 없다.
//
let a = 10;
a.name = function(){};
// 2. 객체자료형 : 속성이나 메서드를 가질 수 있다.
//
/*
1) Object의 속성과 메서드
constructor() : 객체 생성자함수
hasOwnProperty(name) : 인자로 전달된 name라는 속성 존재 여부
isPrototypeOf(객체) : 해당 객체의 prototype인지 여부
propertyIsEnumerable(name) : 해당객체가 반복객체(iterable)즉, 반복문 사용가능 여부
isLocalString() : 객체의 문자셋을 호스트환경에 맞는 문자셋으로 변경
toString() : 객체의 정보를 출력(문자열)
valueof() : 객체의 값을 출력
*/
let obj1 = { key1: 'value1', key2: 'value2'};
let obj2 = new Object();
for(let key in obj1){
document.write(`${key} = ${obj1[key]}<br>`)
}
document.write('<hr>')
for(let key in obj2){
document.write(`${key} = ${obj2[key]}<br>`)
}
</script>
<script>
/*
Number객체는 Object에서 상속받은 메서드와 3개의 메서드
1. toExponential : e지수로 나타낸 문자열을 리턴
2. toFixed : 고정소숫점을 표시
3. toPrecision : 숫자의 길이에 따라 고정소수점을 표시
4. Number에 대한 속성
MAX_VALUE, MIN_VALUE
*/
document.write(Number.MAX_VALUE,'<br>')
document.write(Number.MIN_VALUE,'<br>')
</script>
<script>
// String 객체
// String 객체를 생성하는 방법은 리터럴로 정의하는 방법과 new String() 즉, 생성자함수
// 를 이용하는 방법이 있다.
// 1. 생성하는 방법
let str1 = 'Hello World!!';
let str2 = new String('Hello World!!');
// 2. 속성과 메서드
document.write(` ${str1}<br>`);
document.write(`1. ${str1} 문자열의 길이 = ${str1.length} <br>`);
document.write(`2. str1[0] = ${str1[0]}, ${str2[0]} <br>`);
document.write(`3. charAT(6) = ${str1.charAt(6)} <br>`);
document.write(`4. str1.concat(str2) = ${str1.concat(str2)} <br>`);
document.write(`5. str1.concat(str2) = ${str1.concat(str2)} <br>`);
document.write(`6. str1.indexOf('o') = ${str1.indexOf('o')} <br>`);
document.write(`7. str1.indexOf('o', 6) = ${str1.indexOf('o', 6)} <br>`);
document.write(`8. str1.lastIndexOf('o') = ${str1.lastIndexOf('o')} <br>`);
document.write(`9. str1.replace('o', 'x') = ${str1.replace('o', 'x')} <br>`);
document.write(` ${str1}<br>`);
str1 = str1.replace('o', 'x');
document.write(` ${str1}<br>`);
//indexOf와 search는 검색결과가 없다면 -1을 리턴한다.
//두 메서드의 차이점은 indexOf는 정규식(regular express)을 허용하지 않는다.
//indexOf는 검색위치를 인자로 사용할 수 있지만 search는 검색위치를 사용할 수 없다.
document.write(`10. str1.search('lx') = ${str1.search('lx')} <br>`);
document.write(`11. str1.slice(1, 5) = ${str1.slice(1, 5)} <br>`);//(5-1)번째까지 리턴
let str3 = "홍길동, 홍길순, 손흥민, 이강인";
let arr3 = str3.split(','); //쉼표를 기준으로 문자열을 분리후 배열에 저장
document.write(`12. str1.split(',') = ${arr3.length} : `);
for(let i in arr3){
document.write(`${arr3[i]}/`);
}
document.write('<br>');
document.write(`13. str1.substr(1, 3) = ${str1.substr(1, 3)} <br> `); // start, count
document.write(`14. str1.substring(1, 5) = ${str1.substring(1, 5)} <br> `); // start, end-1
document.write(`15. str1.substring(1) = ${str1.substring(1)} <br> `); // start, 끝까지
document.write(`16. str1.toLowerCase() = ${str1.toLowerCase()} <br> `); // start, 끝까지
document.write(`17. str1.toUpperCase() = ${str1.toUpperCase()} <br> `); // start, 끝까지
// 매서드 체이닝 : 모두 소문자 > 0~10개의 문자를 자르기 >'name' 문자열을 연결
let output = "Hello JavaScript!!!"
output = output.toLowerCase()
output = output.substring(0, 10);
output = output.concat('name');
document.write(output);
document.write(`매서드호출 = ${output}<br>` );
document.write('<br>');
output.toLowerCase().substring(0, 10).concat('name');
document.write(`매서드체이닝 = ${output}` );
</script>
<script>
/*
Array객체
1. 배열을 생성하는 방법 생성자 함수
let arr1 = []
let arr2 = [1,2,3,4]
let arr3 = Array();
let arr4 = Array(number) -> 지정된 number갯수 크기를 갖는 빈 배열객체를 생성
let arr5 = Array(any, ...., any,) -> 매개변수를 요소의 값으로 갖는 배열객체를 생성
2. 속성과 매서드
length : 배열의 크기
push() : 배열끝에 추가
pop() : 맨 뒤의 요소를 꺼내오고 동시에 삭제
slice(start, end) : start ~ (end-1)까지 새로운 배열 객체를 반환, 원본은 변경 안됨
join(문자열) : 배열요소를 문자열로 연결해서 하나의 문자열로 리턴
reverse() : 배열요소를 뒤집기(원본도 바뀜)
sort() : 배열요소를 정렬(원본도 변경)
map() : 원본배열을 가공을 해서 새로운 배열로 리턴(원본은 안바뀜)
filter() : 원본배열에서 특정 조건에 맞는 요소만 모아서 새로운 배열로 리턴
reduce() : 요소들을 주어진리듀서함수를 실행 후에 하나의 결과값을 반환
forEach() : 요소들을 주어진 함수로 각각 전달
concat() : 배열을 합치는 함수
*/
let arr1 = [1,2,3,4,5];
// 1. length
document.write(`1. arr1.length = ${arr1. length}<br>`);
document.write(`2. arr1.push(10) = ${arr1. push(10)} => ${arr1}<br>`);
document.write(`3. arr1.push({},'문자열',()=>{}) = ${arr1. push({},'문자열',()=>{})} => ${arr1}<br>`);
document.write(`4. arr1.pop() = ${arr1.pop()}=>${arr1}<br>`);
document.write(`5. arr1.slice(1, 4) = ${arr1.slice(1, 4)}=>${arr1}<br>`);
let arr2 = [1,2,3,4,5];
document.write(`6. arr2.join('--') = ${arr2.join('--')}=>${arr2}<br>`);
document.write(`7. arr2.reverse() = ${arr2.reverse()}=>${arr2}<br>`);
document.write(`8. arr2.sort() = ${arr2.sort()}=>${arr2}<br>`);
arr2 = [1,4,9,16];
document.write(`9. arr2.map(()=>{}) = ${arr2.map( function(a){ return a*2} )}=>${arr2}<br>`);
document.write(`10. arr2.map(()=>{}) = ${arr2.map( a=>a*2 )}=>${arr2}<br>`);
document.write(`11. arr2.filter(()=>{}) = ${arr2.filter( a=> a>4 )}=>${arr2}<br>`);
// reduce : 1 + 4 + 9 + 16 = 30
const 초기값 = 100;
const total = arr2.reduce((이전값, 현재값)=>이전값 + 현재값, 초기값);
document.write(`12. arr2.reduce(()=>{}) = ${total}<br>`);
// arr2.forEach(a=>console.log(a));
arr2.forEach(a=>{
if(a>4)
console.log(a)
});
document.write(`13. arr1.concat(arr2) = ${arr1.concat(arr2)}=>${arr2}<br>`);
// sort : 객체의 정렬
function Student(name, kor, eng, mat){
this.name = name;
this.kor = kor;
this.eng = eng;
this.mat = mat;
this.getSum = function(){return this.kor + this.eng + this.mat}
this.getAvg = () => this.getSum / 4;
this.toString = function(){
return `이름=${this.name}, 국어=${this.kor}, 영어=${this.eng}, 수학=${this.mat}`
}
}
let students = [];
students.push(new Student('홍길동', 10,10,10))
students.push(new Student('손흥민', 20,10,10))
students.push(new Student('이강인', 30,10,10))
//1. 이름순
// students.sort((a,b)=>{
// return b.getSum() - a.getSum();
// })
// for(let i in students){
// document.write(students[i],toString(),'<br>')
// }
// document.write('<br>')
//2. 총점순
students.sort((a,b) => {
return b.getSum() - a.getSum();
})
for(let i in students){
document.write(students[i].toString(),'<br>')
}
document.write('<br>')
//3. 2등까지만 출력
let std = students.sort((a,b)=>{
return b.getSum() - a.getSum();
}).slice(0, 2);
for(let i in std){
document.write(std[i].toString(),'<br>')
}
// arr2.map(
// ()=>{
// }).filter(
// ()=>{
// }).sort(
// ()=>{
// }
// ).reverse(
// ()=>{
// }
// )
</script>
<script>
/*
Math객체는 수학과 관련된 속성과 매서드를 갖는 객체이다.
자바스크립트의 기본 내장 객체중 유일하게 생성자함수를 사용하지 않는 객체이다.
즉, 객체를 생성하지 않아도 바로 사용할 수 있는 내장객체이다.
random()
round()
ceil() : 전달된 실수값을 기준으로 가장 가까운 큰 정수를 리턴 1.1 -> 2
floor() : 전달된 실수값을 기준으로 가장 가까운 작은 정수를 리턴 1.9 -> 1
trunc() : 전달된 실수값을 소수점 이하는 버리는 함수 1.9 => 1
max(값...) : 전달된 값들 중에서 가장 큰 값을 리턴
min(값...) : 전달된 값들 중에서 가장 작은 값을 리턴
*/
document.write(Math.ceil(1.1), '<br>')
document.write(Math.floor(1.9), '<br>')
document.write(Math.trunc(1.9), '<br>')
document.write(Math.max(1,2,3,4,5), '<br>')
document.write(Math.min(1,2,3,4,5), '<br>')
document.write(Math.round(1.4), '<br>')
document.write(Math.random(1.4), '<br>')
let date = new Date();
// let math = new Math();
Math.random()
</script>
<script>
let date1 = new Date();
// 1. 문자열을 이용한 객체생성
let date2 = new Date('Dec 9 2023');
document.write('<br>');
let date3 = new Date('December 9, 2023, 12:03:03');
document.write(date2,'<br>');
document.write(date3,'<br');
document.write('<br>');
// 2. 숫자를 이용한 객체 생성
document.write('<br>');
date3 = new Date(2023, 3, 9)
document.write(date3, '<br>');
// 3. 매서드
// getXxxx, setXxxx 매서드
// 날짜연산
var now = new Date( )
var bef = new Date(2023,03,01);
// getTime() : 1970.1.1 자정부터 ms를 구하는 메서드
document.write(now.getTime() + '<br>');
var interval = now.getTime() - bef.getTime();
document.write(interval + ' ms <br>');
document.write(Math.floor(interval/(1000 * 60 * 60 * 24))+'일<br>');
// 날짜 간격을 구하는 매서드
Date.prototype.getInterval = function(beforeDate){
var interval;
//양수처리
if(this > beforeDate){
interval = this.getTime() - beforeDate.getTime();
}else{
interval = beforeDate.getTime() - this.getTime();
}
return Math.floor(interval / (1000 * 60 * 60 * 24)
)}
document.write(now.getInterval(bef) + '일<br>');
</script>
<script>
/*
JSON객체
JSON(JavaScript Object Notation)은 자바스크립트의 객체형태의 문자열이다.
"속성(키)":값 of 배열형태를 갖는 데이터형태이다.
1. stringify() : 자바스크립의 객체를 문자열로 변화하는 함수
2. parse() : JSON객체를 자바스크립트 객체로 변화하는 함수
*/
let person = {
name: "홍길동",
age: 100,
gender: "남자",
addr: "조선한양",
arr : [1, 2, 3, 4],
data : { a: "aaa", b:"bbb"},
fn: function(){console.log("JSON의 함수")}
}
document.write(typeof person, '<br>')
let str = JSON.stringify(person);
document.write(typeof str, str,'<br>');
//JSON 형태의 문자열을 JavaScript의 객체로 변환
let obj = JSON.parse(str);
document.write(typeof obj, obj.name, '<br>');
</script>
'일 > javascript' 카테고리의 다른 글
js11_Query (0) | 2023.06.01 |
---|---|
js10_exception (0) | 2023.06.01 |
js08_events (1) | 2023.06.01 |
js07_DOM (0) | 2023.06.01 |
js06_BOM (0) | 2023.05.31 |