#TIL 12일차(JS 메서드 정리[2])

앙꼬·2024년 5월 6일

부트캠프

목록 보기
12/59


📍 숫자 관련 메서드

toFixed(): 주어진 소수점 자릿수로 숫자를 포맷

const number = 10.3456;
const formattedNumber = number.toFixed(2); // "10.35"
console.log(formattedNumber);

toPrecision(): 숫자를 지정된 길이의 문자열로 포맷

const number = 123.456;
const formattedNumber = number.toPrecision(4); // 전체 길이가 4인 문자열로 포맷
console.log(formattedNumber); // "123.5"

toString(): 숫자를 문자열로 변환

const number = 10;
const numberToString = number.toString();
console.log(numberToString); // "10"

parseInt(), parseFloat(): 문자열을 정수 또는 부동 소수점 수로 파싱

const intNumber = parseInt("10"); // 10
const floatNumber = parseFloat("10.5"); // 10.5
console.log(intNumber, floatNumber);

isNaN(): 값이 NaN(Not-a-Number)인지 확인

console.log(isNaN("Hello")); // true
console.log(isNaN(10)); // false

📍 함수 관련 메서드

call(), apply(), bind(): 함수의 컨텍스트를 변경하거나 인수를 전달하여 호출

function greet() {
    console.log(`Hello, ${this.name}`);
}

const person1 = { name: "Alice" };
const person2 = { name: "Bob" };

greet.call(person1); // "Hello, Alice"
greet.apply(person2); // "Hello, Bob"

toString(): 함수를 문자열로 변환

function greet(name) {
    console.log(`Hello, ${name}!`);
}

const greetToString = greet.toString();
console.log(greetToString);

bind(): 함수의 컨텍스트를 설정하고 일부 인수를 고정한 새로운 함수를 반환

function greet(greeting) {
    console.log(`${greeting}, ${this.name}`);
}

const person = { name: "Alice" };
const greetPerson = greet.bind(person, "Hello");

greetPerson(); // "Hello, Alice"
profile
프론트 개발자 꿈꾸는 중

0개의 댓글