型别转换 Type Transform
Node.js 型别转换 Type Transform
Categories:
转换成整数 Number
const inputValue = '4';
// good
const val = Number(inputValue);
// good
const val = parseInt(inputValue, 10);
转换成字串 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);