js 判断值大于-1
~
:位非--类似取负数并-1- -1 = -(-1) - 1
let str = "index";
if(~str.indexOf('r')){}
js 去除数据的最外层引号
new Function()
:在使用时,编译器会将参数中的字符串当作正常的脚本代码来执行。
new Function('return ' + '0.34')(); //0.34
new Function('return ' + '{"name":"admin","age":"18"}')(); //{name:'admin',age:'18'}
js 拷贝对象/数组
...
: 展开语法(Spread syntax), 可以在函数调用/数组构造时, 将数组表达式或者string在语法层面展开
let obj = {'name':'admin','age':18,'hobbies':[{'name':'run'},{'name':'sing'}]};
let copyObj = {...obj}; // {name: 'admin', age: 18, hobbies: Array(2)}
let arr = [{'name':'admin1','age':18,'tags':{'name':'young'}},{'name':'admin2','age':18,'tags':{'name':'young'}}];
let copyArr = [...arr]; // (2) [{…}, {…}]
let arr1 = [{'name':'admin1','age':18,'hobbies':[{'name':'run'},{'name':'sing'}]},{'name':'admin2','age':18,'hobbies':[{'name':'run'}]}];
let copyArr1 = [...arr]; // (2) [{…}, {…}]
js 保留一定小数位
toFixed(Number)
: 四舍六入五考虑,五后非零就进一,五后为零看奇偶,五前为偶应舍去,五前为奇要进一。
100.toFixed(2); //'100.00'
js 转换为二进制
toString(Number)
: 返回Number对象的字符串表示形式。 它接受一个可选参数来设置基数。
Number(10).toString(2); //'1010'
js 二进制转为十进制
parseInt(二进制字符串,radix = 2)
:可解析一个字符串,并返回一个整数。
parseInt('1010',2); //10
js 时间数不足两位前面补零
padStart(length , padString)
: 字符串不足要求的长度时会在字符串前面重复加上补充的字符串。
'3'.padStart(2,'0'); //'03'
js 格式化日期展示
该字符串格式与系统设置的地区关联(locality sensitive)。
例如,在美国,月份出现在日期(06/22/2018)之前,而在印度,日期出现在月份(22/06/2018)之前。
console.log(`${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}`)
js 快速获取时间戳
getTime 方法的返回值一个数值,表示从1970年1月1日0时0分0秒(UTC,即协调世界时)距离该日期对象所代表时间的毫秒数。
console.log(+new Date())
console.log(new Date()*1)
console.log(new Date().valueOf())
console.log(new Date().getTime())
js 浮点数精度 / 误差范围
Number.EPSILON: 属性的值接近于 2.2204460492503130808472633361816E-16,或者 2-52。
Number.EPSILON: 实际上是 JavaScript 能够表示的最小精度。误差如果小于这个值,就可以认为已经没有意义了,即不存在误差了。
Number.EPSILON === Math.pow(2, -52)
// true
Number.EPSILON
// 2.220446049250313e-16
console.log(0.1 + 0.2 - 0.3 < Number.EPSILON) //true
js 判断NaN相等,以及正负零
- NaN 即 window.NaN 是es5 的,Number.NaN 是 es6 的
- NaN等于自身
console.log(-0 == +0) //true
console.log(-0 === +0) //true
console.log(Object.is(+0,-0)) //false
console.log(NaN == Number.NaN) //false
console.log(NaN == Number.NaN) //false
console.log(Object.is(NaN, Number.NaN)) //true
js 可选链操作符-?.
在寻找树状结构深处的属性值时,通常必须检查中间节点是否存在
const res = travelPlans?.tuesday?.location?.href;
js 非空运算符-??
如果第一个参数不是 null/undefined(这里只有两个假值,但是 JS 中假值包含:未定义 undefined、空对象 null、数值 0、空数字 NaN、布尔 false,空字符串'',不要搞混了),将返回第一个参数,否则返回第二个参数。
let num = 0;
res = num ?? 1 //在有些时候只想验证对象是否存在而不考虑零或者空字符串时很有用