고군분투 개발 공부
방명록 RSS 태그 글쓰기 관리자
 
[FreeCodeCamp] Testing Objects for Properties
JavaScript 2022-12-23 10:42:11

Sometimes it is useful to check if the property of a given object exists or not. We can use the .hasOwnProperty(propname) method of objects to determine if that object has the given property name. .hasOwnProperty() returns true or false if the property is found or not.

Example

const myObj = {
  top: "hat",
  bottom: "pants"
};

myObj.hasOwnProperty("top");
myObj.hasOwnProperty("middle");

The first hasOwnProperty returns true, while the second returns false.

 

Modify the function checkObj to test if an object passed to the function (obj) contains a specific property (checkProp). If the property is found, return that property's value. If not, return "Not Found".

 

  • Passed:checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "gift") should return the string pony.
  • Passed:checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "pet") should return the string kitten.
  • Passed:checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "house") should return the string Not Found.
  • Passed:checkObj({city: "Seattle"}, "city") should return the string Seattle.
  • Passed:checkObj({city: "Seattle"}, "district") should return the string Not Found.
  • Passed:checkObj({pet: "kitten", bed: "sleigh"}, "gift") should return the string Not Found.

 

\

 

function checkObj(objcheckProp) {
  if (obj.hasOwnProperty(checkProp)) {
    return obj[checkProp];
  } else {
    return "Not Found";
  }
}

 

 



프로퍼티
JavaScript 2022-12-21 19:42:38

요소 노드에 대한 이동 프로퍼티

element.children 자식 요소 노드 element의 자식 요소 모음(HTMLCollection)
element.firstElementChild 자식 요소 노드 element의 첫 번째 자식 요소 하나
element.lastElementChild 자식 요소 노드 element의 마지막 자식 요소 하나
element.parentElement 부모 요소 노드 element의 부모 요소 하나
element.previousElementSibling 형제 요소 노드 element의 이전(previous) 혹은 좌측(left)에 있는 요소 하나
element.nextElementSibling 형제 요소 노드 element의 다음(next) 혹은 우측(right)에 있는 요소 하나

 

모든 노드에 대한 이동 프로퍼티

node.childNodes 자식 노드 node의 자식 노드 모음(NodeList)
node.firstChild 자식 노드 node의 첫 번째 자식 노드 하나
node.lastChild 자식 노드 node의 마지막 자식 노드 하나
node.parentNode 부모 노드 node의 부모 요소 하나
node.previousSibling 형제 노드 node의 이전(previous) 혹은 좌측(left)에 있는 노드 하나
node.nextSibling 형제 노드 node의 다음(next) 혹은 우측(right)에 있는 노드 하나

 

DOM 트리를 구성할 때..

브라우저가 HTML 코드를 해석할 때 각 코드들은 상황에 맞게 node를 생성하고 DOM 트리를 구성하는데,

HTML 태그요소 노드가 되고, 문자들텍스트 노드, 그리고 주석주석 노드로 DOM 트리에 반영됨

<!DOCTYPE HTML>
<html>
<head>
  <title>JavaScript</title>
</head>
<body>
  I Love JavaScript
  <!-- I Love Codeit -->
</body>
</html>

 

 



[JavaScript] 객체가 비어있는지 확인하기 - 프로퍼티 체크
JavaScript 2022-12-15 17:44:57

객체에 프로퍼티가 하나도 없는 경우 true, 그렇지 않은 경우 false를 반환해주는 함수 isEmpty(obj)를 만들기

 

function isEmpty(obj){
	for (let key in obj){
    return false;
    }
    return true;
   }

 

이 간단한 코드가 뭐라고



[JavaScript] 예제와 정보 참고 : MDN JavaScript Reference
JavaScript 2022-12-14 23:27:35

매뉴얼

  • Mozilla 재단이 운영하는 MDN JavaScript Reference엔 다양한 예제와 정보가 있습니다. 특정 함수나 메서드에 대한 깊이 있는 정보를 얻고 싶다면 이 사이트가 제격입니다.위 사이트에 들어가서 원하는 내용을 직접 검색하는 것도 좋지만, 가끔은 검색 엔진을 이용해 내용을 찾는 게 더 나을 때도 있습니다. Google 검색 엔진에 접속해 'MDN [원하는 용어]'를 입력해 봅시다. parseInt 함수에 대한 정보를 얻고 싶다면 https://google.com/search?q=MDN+parseInt 같이 검색하는 식으로 말이죠.
  • 링크는 다음과 같습니다. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference

 



[JavaScript] 생성자 함수
JavaScript 2022-12-14 15:57:06

생성자 함수 : 붕어빵 틀이나 와플팬이라고 생각하면 됨. 필요한 재료를 넣고 찍어내기..

필요한 재료는 이름과 나이

와플은 생성되는 객체

function User(name, age){
		//첫글자는 대문자로
	this.name=name;
    this.age=age;
   }
   
   
let user1=new User('Mike', 30);
let user2=new User('Jane', 22);
let user3=new User('Tom', 17);
		 //new 연산자를 사용해서 호출
         

console.log(user1);
console.log(user2);
console.log(user3);

<출력결과>

User {

name: "Mike",

age:30

}

User {

name: "Jane",

age:22

}

User {

name: "Tom",

age:17

}

 


function User(name, age){
  this.name=name;
  this.age=age;
  this.sayName=function(){
    console.log(this.name);
  }
}

let user5=new User('Han', 40);
user5.sayName(); //'Han'

 


 

function Item(title, price){
  //this={};
  this.title=title;
  this.price=price;
  this.showPrice=function(){
    console.log(`가격은 ${price}원 입니다.`)
  }
  
  //return this;`
}

const item1= new Item('인형', 3000);
const item2= new Item('가방', 4000);
const item3= new Item('지갑', 9000);

console.log(item1, item2, item3);

item3.showPrice();

 

<출력결과>

(item3.showPrice();)

가격은 9000원 입니다.



[JavaScript] 객체와 메소드의 관계 - this
JavaScript 2022-12-14 13:42:53

const user={
	name: "Mike",
	sayHello: function(){
		console.log(`Hello, I'm ____`);
		}
	}

 

객체의 name property를 넣고 싶다면?

(`Hello, I'm ${user.name}`)

 

-> 문제 발생할 수 있음.

 

이럴 때 this라는 키워드를 사용하면 됨.

 


 

let boy={
	name:"Mike",
	}



let girl={
	name:"Jane",
	}



sayHello: function(){
	console.log(`Hello, I'm ${this.name}`);
	}

 

여기서 this는 아직 결정되지 않았다.

어떻게 호출하느냐에 따라 달라지게 됨.

이제 이 함수를 각 객체의 메소드로 넣어주자...

 

boy.sayHello(); // I'm Mike
girl.sayHello(); // I'm Jane

sayHello: function() {
	console.log(`Hello, I'm ${this.name}`);
    }

 

 

*** 화살표 함수는 일반 함수와 달리 자신만의 this를 갖고 있지 않기 때문에 this를 외부에서 가져온다.

this는 어렵다.. 어렵다..! 

공부 따로 다시 하자!!!

 

 

 

참고 페이지

https://hanamon.kr/javascript-this%EB%9E%80-%EB%AC%B4%EC%97%87%EC%9D%BC%EA%B9%8C/

 

[JavaScript] this 란 무엇일까? - 하나몬

자바스크립트의 this의 정의부터 용법까지 ⚡️ this의 정의 ❗️this란? this란 ‘이것’ 이란 뜻이다. this란 JavaScript 예약어다. ❗️this는? this는 자신이 속한 객체 또는 자신이 생성할 인스턴스를

hanamon.kr

 



[JavaScript] for..in (객체 호출 활용)
JavaScript 2022-12-14 13:12:07

const Mike={
  name: "Mike",
  age: 30,
};

for (x in Mike){
  console.log(x)
};

<출력결과>

"name"

"age"

 

const Mike={
  name: "Mike",
  age: 30,
};

for (x in Mike){
  console.log(Mike[x])
};

<출력결과>

"Mike"

"30"



[JavaScript] isAdult 함수
JavaScript 2022-12-14 13:07:17

function isAdult(user){
  if(!('age' in user) || user.age<20){
    return false;
  }
  return true;
}

const Mike={
  name: "Mike",
  age: 30,
}

const Jane={
  name: "Jane",
}

console.log(isAdult(Jane));

<출력결과>

false



[JavaScript] 함수로 Object 만들기
JavaScript 2022-12-13 22:44:28

 

function makeObject(name, age){
  return{
    name: name,
    age: age,
    hobby: 'football',
  };
}

const Mike=makeObject('Mike', 30);
console.log(Mike);

<출력결과>

 



[JavaScript] 함수 선언문 vs 함수 표현식
JavaScript 2022-12-13 12:30:37

함수 선언문

function sayHello(){
	console.log('Hello');
}

sayHello();

-> 어디서든 호출 가능 : sayHello()의 위치가 어디어도 동작 가능함. 

(자바스크립트 내부 동작방식에 의한 현상 - '호이스팅')

 

 

함수 표현식

(이름이 없는 함수를 만들고 변수를 선언해서 함수를 할당해줌)

let sayHello=function(){
	console.log('Hello')
}

sayHello();

-> 코드에 도달하면 생성, 그 이후에 사용가능.




이 사이트에는
넥슨코리아에서 제공한 넥슨 Lv.1 고딕 Regular체,
카페24가 제작한 아네모네체,
Cadson Demak가 디자인한 Kanit체,
Sandoll이 디자인한 나눔고딕체가
적용되어 있습니다.
멋진 폰트를 무료로 제공해주셔서 감사합니다.

Copyleft ⓒ bskyvision (블루스킨 v1.2)