<!DOCTYPE html>
<meta charset="UTF-8">
<script>
var aa = {
"name": "ppp",
["ojh"]:"qqq"
}
//자바스크립트에서 function 키워드는 class의 의미로도 사용될 수 있음(중요!)
function MyArray(){
this.length = 0; //배열에는 length 속성이 있음
/* 메소드는 메모리를 아낄 필요가 있음
this.push = function(param){ // 메소드추가
this[this.length] = param; //배열아니고 JSON의 배열식 접근법!
this.length++;
}
*/
return this; // class의 의미로 쓰일 때는 요거이 생략되어 있음 // 만들고 있는 애를 나중에 리턴! 위의 this 모두 같은 놈
}
// 명시적으로 prototype에 정의해야 같은 class에서 나온 객체가
// 메소드를 공유할 수 있음(메모리절약 효과)
MyArray.prototype.push = function(param){
this[this.length] = param;
this.length++;
}
// 조건에 맞는 첫번째 값을 리턴! 요즘 자주 쓰이는 메소드
MyArray.prototype.find = function(pcb){
for(var i=0;i<this.length;i++){
if(pcb(this[i])){ // 조건에 맞으면 // 참일때만 조건을 돌음!
return this[i]; // 해당값 리턴!
}
}
} // 콜백함수로 배열이 가지고 있는 값을 하나씩(pcb(this[i])) 가져다 주면 true면 값을 리턴함
// MyArray.prototype.push = function(pcb){
// var schResult = []; // 찾은 걸 담을 배열/ new MyArray 가능
// for(var i=0; i<this.length; i++){
// if(pcb(this[i],i)){ //다 찾아야만 리턴가능
// schResult.push(this[i]); // 배열에 담기
// }
// }
// return schResult;
// }
// 찾은 것들을 모아서 배열로 리턴!
MyArray.prototype.filter = function(pcb){
var schResult = []; // 찾은 걸 담을 배열/ new MyArray 가능
for(var i=0; i<this.length; i++){
if(pcb(this[i],i)){ //다 찾아야만 리턴가능
schResult.push(this[i]); // 배열에 담기
}
}
return schResult;
}
MyArray.prototype.some = function(pcb){
for(var i=0; i<this.length; i++){
if(pcb(this[i])){
return true;
}
}
return false;
}
MyArray.prototype.every = function(pcb){
for(var i=0; i<this.length; i++){
if(!pcb(this[i])){ // 조건에 만족하지 않으면 // 콜백함수가 false일때!
return false; // 거기서 끝내버림
}
}
return true; // for문 다 돌때까징 조건에 만족하지 않은게 없다면
// 곧 모두 조건에 만족한다면 true
// 위에서 하나도 false가 생기지 않으면 최종적으로 true 리턴
}
var OJH = new MyArray();
for(var i=0; i<10; i++){
OJH.push(Math.ceil(Math.random() * 10) + i);
}
console.log(OJH);
console.log("find:" , OJH.find(function(param){ // 매개변수로 함수를 받아서 콜백함수 위에서 function(pcb) 받아옴 / 그래서 매개변수 param필요
return param > 10; // 위에서 참인거 돌아서 찾아주는게 find(function) 리턴 1개!
// 조건에 맞는 첫번째 값을 리턴
}));
// ! ! ! 클래스를 만들어 쓴다는 것은 사용자 정의 데이타 type 확인! ! !
console.log("filter:" , OJH.filter(function(param){
return param > 10;
}));
console.log("some:" , OJH.some(function(param){
return param > 20;
}));
console.log("every:" , OJH.every(function(param){
return param < 20;
}));
</script>