728x90
반응형

배열 검색 - 일치하지 않는 것을 찾지 못하면 –1을 반환한다 

indexOf() lastIndexOf() lastIndexOf()

 

const o9 = { name : "Jerry" };

const array9 = [1, 5, "a", o, true, 5, [1, 2], "9"];

array9.indexOf(5); // 1

array9.lastIndexOf(5); // 5 마지막 인덱스에 가까운 번호가 저장

array9.lastIndexOf(5, 4); // 1 두 번째 매개변수 값은 검색을 끝낼 인덱스 값이다

 

 

findIndex()는 indexOf 보다 더욱 다양한 상황에서 활용할 수 있다

const array10 = [{ id : 5, name : "Judith" }, { id : 7, name : "Francis" }];

array10.findIndex(o => o.id === 5); 0

array10.findIndex(o => o.name === "Francis"); 1

array10.findIndex(o => o === 3); -1

array10.findIndex(o => o.id === 17); -1

배열 검색 메서드

콜백함수를 사용하는 모든 메서드는 호출할 때 this로 사용할 값을 두 번째 매개변수로 받을수 있다

콜백함수 사용시 return 값이 ture인 요소를 찾을 때까지 순회하다가 찾으면 끝이난다

 

find()는 요소 자체를 검색하려할 때

const array10 = [{ id : 5, name : "Judith" }, { id : 7, name : "Francis" }]; json 데이터에 대한 검색

array10.find(o => o.id === 5); { id : 5, name " Juditj" } 요소 자체를 검색이된다

array10.find(o => o.id === 2); undefined

 

const array11 = [1, 17, 16, 5, 4, 16, 10, 3, 49];

array11.find((x, y) => i > 2 && Number.isInteger(Math.sqrt(x))); // 4

 

 

find findIndex에 전달하는 함수의 this도 수정할 수 있다. 이를 이용해서 함수가 객체의 메서드인 것처럼 호출할 수 있다

 

ID를 조건으로 Person 객체를 검색하는 방법의 예제를 확인하자

class Person {

constructor(name){

this.name = name;

this.id = Person.nextId++;

}

}

Person.nextId = 0; Person.nextId 초기값 0을 설정하고 객체가 생성될 때마다

const jamie = new Person("Jamie"); ++증가식이되어 id에 +1씩 된다

juliet = new Person("Juliet");

peter = new Person("peter");

jay = new Person("Jay");

const array17 = [jamie, juliet, peter, jay];

 

 

* 옵션 1 : ID를 직접 비교하는 방법

array17.find(p => p.id === juliet.id); juliet 객체이며, 무명함수를 주로 사용한다 그리고 매개변수 인자값으로

선언되는 것은 배열의 주소를 뜻한다

 

* 옵션 2 : "this" 매개변수를 이용하는 방법

array17.find(function (p){ find() 콜백함수 사용시 return 값이 ture인 요소를

return p.id === this.id 찾을 때까지 순회하다가 찾으면 거기서 끝납니다

}, juliet); juliet 객체

 

728x90
반응형

+ Recent posts

Powered by Tistory, Designed by wallel