본문 바로가기

언어/Javascript

prototype.includes(), in 연산자, hasOwnProperty(), Array.prototype.some

in 연산자는 객체에 사용하는 용도 이다.

즉 객체가 갖는 프로퍼티와 메소드 존재 여부를 검증해 true, false로 리턴한다.

이 때 주의할 점은 배열 사용시, 내용이 아닌 인덱스 값을 검증한다.

var soccerplayer = new Array("nedved", "ronaldo", "ronaldinho", "henry", "jisungpark");

"henry" in soccerplayer // false
length in socerplayer // true

 

즉 내용을 찾는 검증을 위해 쓰면 안되고, 프로퍼티가 있는지, 메소드가 존재하는지를 검증하기 위해 사용해야만 한다.

 

그렇다면 문자열이나 배열에서 값을 검증하고 싶을 때는 어떻게 하나ㅏ?

그럴 때,  ES6에서 추가 된 메서드 includes()를 사용한다.

soccerplayer.includes("henry"); // true
soccerplayer.includes(length); // false

"henry".includes("ry") // true

includes 는 값을 검증하고 boolean값을 리턴한다.

즉 , 

String.includes( someString, length )

Array.includes( someString, length )

someString : 검색할 문자열
length : (Optional)검색을 시작 할 위치. length를 생략하면 전체 문자열을 탐색.

 

 

그렇다면 hasOwnProperty() 는 무엇인가?

hasOwnProperty()는 in과 같은 역할이다. 해당 객체 안에 프로퍼티나 메소드가 있는 지 검증한다.

그렇다면 누가 길게 hasOwnProperty()를 쓰겠어? 할 수 있지만,

in은 prototype 메서드 까지 포함해 검증하지마, hasOwnProperty는 prototype메서드는 검증하지않는다.

그 외에도 hasOwnPrototype이 자식 객체라면 부모에게 상속받은 메서드나 프로퍼티는 검증하지 않는다.

실제 그 객체가 가진 프로퍼티나 메서드만 검증.

"toString" in objs // true
 
objs.hasOwnProperty("toString") // false

Array.prototype.some은  배열을 순회하면서 인수로 전달 된 콜백함수가 호출된다.

이 때 콜백함수 조건에 대한 반환값이 한번이라도 참이면 true, 아니면 false.

 

const soccerplayer = new Array("nedved", "ronaldo", "ronaldinho", "henry", "jisungpark");
soccerplayer.some(item=>item === "henry"); // true

'언어 > Javascript' 카테고리의 다른 글

집합의 교집합 차집합 대칭차집합  (0) 2022.08.14
Array.prototype.join()  (0) 2022.08.12
.sort()  (0) 2022.08.10
Objects.entries(arr)  (0) 2022.08.10
객체 순회  (0) 2022.08.08