프로그래밍 공부/Javascript

toString()

Kevinkb 2021. 6. 24. 12:16

Object.prototype.toString()

toString() 메서드는 문자열을 반환하는 object의 대표적 방법이다.

object.toString()

예시

문자열 타입으로 전환

let test1 = true;
let test2 = 324241;
let test3 = [1, 2, 3];
console.log(test1.toString());           //  'true'
console.log(test2.toString());           //  '324241'
console.log(test3.toString());           //  '1,2,3'
console.log(typeof test1.toString());    //  string
console.log(typeof test2.toString());    //  string
console.log(typeof test3.toString());    //  string

커스텀 객체의 toString() 메서드를 호출하는 경우 Object로부터 상속받은 기본 값을 반환한다.

function Dog(name, breed, color, sex) {
  this.name = name;
  this.breed = breed;
  this.color = color;
  this.sex = sex;
}

theDog = new Dog('Gabby', 'Lab', 'chocolate', 'female');

theDog.toString(); // [object Object]

객체 클래스 검사

var toString = Object.prototype.toString;

toString.call(new Date);    // [object Date]
toString.call(new String);  // [object String]
toString.call(Math);        // [object Math]

// Since JavaScript 1.8.5
toString.call(undefined);   // [object Undefined]
toString.call(null);        // [object Null]

Array.prototype.toString()

toString() 메서드는 지정된 배열 및 그 요소를 나타내는 문자열을 반환한다.

array.toString()

반환 값

배열을 표현하는 문자열을 반환한다.

설명

toString 메서드는 배열을 합쳐(join) 쉼표로 구분된 각 배열 요소를 포함하는 문자열 하나를 반환한다.

예시

const array1 = [1, 2, 'a', '1a'];

console.log(array1.toString());   // "1,2,a,1a"

var monthNames = ['Jan', 'Feb', 'Mar', 'Apr'];

var myVar = monthNames.toString(); // 'Jan,Feb,Mar,Apr'을 myVar에 할당.

Number.prototype.toString()

toString() 메서드는 특정한 Number 객체를 나타내는 문자열을 반환한다.

numberObject.toString([radix])

매개변수

radix(Optional) : 수의 값을 나타내기 위해 사용되는 기준을 정하는 2와 36사이의 정수. (진수를 나타내는 값)

  • 기본 값은 10진수.
  • numberObject가 음수라면 - 부호는 유지

반환 값

Number 객체를 명시하는 문자열. radix가 2~36 사이의 값이 아니면 에러 발생

예시

var count = 10;

console.log(count.toString());    // displays '10'
console.log((17).toString());     // displays '17'
console.log((17.2).toString());   // displays '17.2'

var x = 6;

console.log(x.toString(2));       // displays '110'
console.log((254).toString(16));  // displays 'fe'

console.log((-10).toString(2));   // displays '-1010'
console.log((-0xff).toString(2)); // displays '-11111111'

'프로그래밍 공부 > Javascript' 카테고리의 다른 글

키보드 이벤트, input 태그, 스크롤 이벤트  (0) 2021.06.24
화살표 함수  (0) 2021.06.24
reverse(), join(), split(), includes()  (0) 2021.06.23
비표준 속성 다루기  (0) 2021.06.23
마우스 이벤트  (0) 2021.06.23