Web/Javascript

[Javascript] 객체

Untitled_Blue 2023. 8. 8. 21:51
반응형

안녕하세요. 이번 글은 객체에 대한 설명입니다.

- 객체란?

  • 속성의 집합체이며 하나의 사물을 정의한다.
  • 배열 안에는 위치를 나타내는 인덱스와 위치 내에 있는 데이터인 요소로 구성되어있다.
  • 객체의 종류는 대표적으로 배열, 함수, 날짜, 정규 표현식 등이 있다.
<html lang="en">
<head>
    <title>Document</title>
</head>
<script>
    const blog_info = {
        이름 : 'Untitled_Blue',
        소속 : 'Tistory',
        블로그생성일 : '2023.03.11'
    };

    document.write(blog_info.이름 + "<br>");
    document.write(blog_info.소속 + "<br>");
    document.write(blog_info.블로그생성일);
</script>
<body>
</body>
</html>

다음과 같이 하나의 객체 안에 쉼표를 기준으로 여러 개의 요소를 설정할 수 있으며 요소 안에는 키와 값으로 구성되어 있다는 점을 확인할 수 있다.

const blog_info = {
  이름 : 'Untitled_Blue',
  소속 : 'Tistory',
  블로그생성일 : '2023.03.11'
};

document.write(blog_info['이름'] + "<br>");
document.write(blog_info['소속'] + "<br>");
document.write(blog_info['블로그생성일']);

다음과 같이 객체명['요소의 키 이름']으로 호출해도 정상적으로 내부의 값이 출력됨을 확인할 수 있다.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<script>
    const blog_info = {
        이름 : 'Untitled_Blue',
        소속 : 'Tistory',
        블로그생성일 : '2023.03.11',

        mIntroduce: function(val) {
            document.write(val + this.이름 + "블로그는 현재 " + this.소속 + " 플랫폼에 소속되어 있으며 " + this.블로그생성일 + "날에 활동을 시작했습니다.");
        }
    };

    document.write(blog_info['이름'] + "<br>");
    document.write(blog_info['소속'] + "<br>");
    document.write(blog_info['블로그생성일'] + "<br>");

    blog_info.mIntroduce('자기소개 시작 ! : ');
</script>
<body>
</body>
</html>

다음과 같이 키에 대한 값으로 함수를 선언할 수 있으며 객체명.키의이름을 통해서 호출할 수 있다는 점을 확인 가능하다.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<script>
    const blog_info = {
        이름 : 'Untitled_Blue',
        소속 : 'Tistory',
        블로그생성일 : '2023.03.11',

        mIntroduce: function(val) {
            document.write(val + this.이름 + "블로그는 현재 " + this.소속 + " 플랫폼에 소속되어 있으며 " + this.블로그생성일 + "날에 활동을 시작했습니다.");
        }
    };

    document.write(("이름" in blog_info) + "<br>"); // true
    document.write("종류" in blog_info);            // false
</script>
<body>
</body>
</html>

객체에 대한 내부 요소를 호출하는 것 외에도 객체 안에 해당 키가 존재하는지에 대한 여부 또한 확인할 수 있다.

사용하는 방법은 "[KEY]" in Object 이며 객체 안에 키의 존재를 확인하기 위함이며 반환값은 논리 자료형이다.

 

- Number 객체

메서드명 설명
toFixed() 숫자 N번째 자릿수까지 출력하는 메서드
isNaN() 숫자가 맞는지 아닌지를 반환하는 메서드
isFinite() 무한대의 숫자인지를 판별하는 메서드
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<script>
    const a = "";
    const b = 20;
    const c = 3.14567891235;

    document.write(Number.isNaN(a) + "<br>"); // true
    document.write(Number.isFinite(b) + "<br>"); // false
    document.write(c.toFixed(2)); // 3.15 (자동 반올림 처리)
</script>
<body>
</body>
</html>

다음과 같이 Number 객체에 대한 3가지 메서드가 저마다의 기능을 구현한다는 점을 확인할 수 있다.

- String 문자열 객체

메서드 설명
.length 문자열의 길이를 반환
.toUpperCase(), .toLowerCase() 문자열을 대문자 또는 소문자로 변환
.split() 문자열을 특정 기호를 기준으로 배열 단위로 나눔
.trim() 문자열 양쪽 끝의 공백 제거
.concat() 두 개 이상의 문자열을 하나로 통합
.replace() 문자열 내 특정 문자를 다른 문자로 교체
.substring() 문자열 내 위치값을 시작으로 몇 번째 문자열 위치까지 출력
.substr() 문자열 내 위치값을 기준으로 몇 글자까지만 출력
.charAt() 문자열 내 특정 위치값의 문자 단위를 출력
<html lang="en">
<head>
    <title>Document</title>
</head>
<script>
    const a = "Hello. JavaScript!";

    document.write(a.charAt(1) + "<br>");
    document.write(a.substring(7, a.length) + "<br>");
    document.write(a.substr(7, 10) + "<br>");
    document.write(a.concat(" Nice to meet You :)") + "<br>");
    document.write(a.split(' ') + "<br>");
    document.write(a.toLowerCase() + "<br>");
    document.write(a.toUpperCase());
</script>
<body>
</body>
</html>

다음과 같이 문자열에 대한 메서드를 사용할 수 있음을 확인할 수 있으며 이는 객체지향 프로그래밍 언어 내 String 관련 메서드와 매우 유사함을 확인할 수 있다.

- Math 객체

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<script>
    document.write(Math.PI + "<br>");
    document.write(Math.sqrt(16) + "<br>");
    document.write(Math.abs(-3.3) + "<br>");
    document.write(Math.ceil(5.42) + "<br>");
    document.write(Math.round(5.42) + "<br>");
    document.write(Math.floor(5.61) + "<br>");
    document.write((Math.random() * 10) + "<br>");
    document.write(Math.E);
</script>
<body>
</body>
</html>

다음과 같이 Math 객체를 통해 반올림, 올림, 내림, 절댓값, 파이, 제곱근 등과 같은 다양한 수학함수 뿐만 아니라 프로그램을 실행할 때마다 다른 값을 나타내주는 random() 함수도 존재함을 확인할 수 있다. 상단의 코드 이외에도 sin, cos, tan 같은 삼각함수도 존재한다. 나머지 다양한 Math 객체에 대한 함수는 하단 링크를 참고하면 좋다.

https://www.w3schools.com/js/js_math.asp

 

JavaScript Math Object

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

 

다음 글은 문서 객체 모델인 DOM에 대한 설명입니다. 감사합니다.

반응형