型別轉換 Type Transform

Node.js 型別轉換 Type Transform

轉換成整數 Number

const inputValue = '4';

// good
const val = Number(inputValue);

// good
const val = parseInt(inputValue, 10);

型別轉換 Type Transform

轉換成字串 String

let reviewScore = 9;

// good
const totalScore = String(reviewScore);

// bad: typeof totalScore is "object" not "string"
// const totalScore = new String(reviewScore);

// bad: invokes this.reviewScore.valueOf()
// const totalScore = reviewScore + '';

// bad: isn’t guaranteed to return a string
// const totalScore = reviewScore.toString();

轉換成布林 Boolean

const age = 0;

// best
const hasAge = !!age;

// good
const hasAge = Boolean(age);

// wrong: is an Object
// const hasAge = new Boolean(age);

參考資料