-
Notifications
You must be signed in to change notification settings - Fork 83
Open
Labels
Description
再次分享几个 tricks
- number convert to String (数字转字符串)
这个大家用的都比较多了,就是连接一个空字符串即可
const val = 1 + ''; // Or ''+1
console.log(val); //输出 '1'
console.log(typeof val); //输出 'string'- string convert to number (字符串转数字)
这个大家肯定会,比如用 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- Float to Integer(小数转整数)
你可以使用Math.floor(), Math.ceil(), Math.round() , 你也可以更好的使用 |, 位运算符OR, 特点是: 正数向下取整、负数向上取整
console.log(23.9 | 0); // 输出: 23
console.log(-23.9 | 0); // 输出: -23- Format JSON Code (格式化json)
你肯定用过 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"
}
}
*/