[JavaScript] 객체의 length

jee-woo·2022년 7월 13일
0

자바스크립트

목록 보기
5/8

객체의 length?

length 메서드는 배열과 문자열(String)에서만 사용 가능하다.
따라서 객체에는 length 메서드를 사용할 수 없다.

객체의 길이를 구하는 방법

Object.keys()를 사용하면 객체의 key값들로 구성된 배열을 리턴 받는다.

let song = {
  artist: "Nayeon",
  title: "POP!",
}
let keys = Object.keys(song);
console.log(keys);	// ['artist', 'title'];

이제 keys 배열의 길이를 구하면 song 객체의 길이와 같은 값을 구할 수 있다.

let songLength = keys.length;
console.log(songLength);	// 2
profile
FE Developer

0개의 댓글