itstrive / striveCode

some demo and js Knowledge points records :cn: :cloud: :snowflake:
108 stars 83 forks source link

convert type tricks #15

Open itstrive opened 5 years ago

itstrive commented 5 years ago

再次分享几个 tricks

这个大家用的都比较多了,就是连接一个空字符串即可

const val = 1 + ''; // Or ''+1

console.log(val); //输出 '1'
console.log(typeof val); //输出 'string'

这个大家肯定会,比如用 Number,或者parseInt、parseFloat都可以

当然更方便的是用 +

let int = '600';
int = +int;
console.log(int);
let int = +'600';
console.log(int);

当然也可以转boolean为number:

let int = +true; //1
let int2 = +false; //2

你可以使用Math.floor(), Math.ceil(), Math.round() , 你也可以更好的使用 |, 位运算符OR, 特点是: 正数向下取整、负数向上取整

console.log(23.9 | 0);  // 输出: 23
console.log(-23.9 | 0); // 输出: -23

你肯定用过 JSON.stringify() ,但是你未必用过它其他参数

JSON.stringify(需要格式化的json对象,replace函数,格式化的空格)

const user = {
    name:'strive',
    age:18,
    details:{
        email:'xxx@xx.com'
    }
}

console.log(JSON.stringify(user, null, '\t'));

//输出:
/*
{
    "name": "strive",
    "age": 18,
    "details": {
        "email": "xxx@xx.com"
    }
}
*/