js运算符的奇淫技巧(继续更新中)

本文深入探讨JavaScript中各类数据类型的转换技巧,包括字符串转数字、时间格式转时间戳、任意类型转布尔值、数字取整等实用操作。通过具体示例展示如何使用+、!!、~~等运算符进行高效类型转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、+ 任意类型转number

var str = '123';
var num = +str;//这里可以用减号吗,答案肯定是可以,可以转成number,只不过是负数,在这里就是-123
console.log(typeof num);//number

console.log(+{});//NaN
console.log(+undefined);//NaN
concole.log(+[]);//0
concole.log(+null);//0
复制代码

2、+ UTC时间格式转时间戳,以下三种想法结果相同

console.log(Date.parse(new Date()));
console.log(new Date("2019/4/25").getTime());
console.log(+new Date());
复制代码

3、!! 任意类型转boolean

console.log(!![]);//true
console.log(!!{});//true
console.log(!!-1);//true
console.log(!!1);//true
console.log(!!'abc');//true
console.log(!!'');//false
console.log(!!0);//false
console.log(!!undefined);//false
console.log(!!null);//false
复制代码

4、 ~~ 任意类型转number更加友好,正数向下取整,负数向上取整

console.log(~~'123');//123
console.log(~~[]);//0
console.log(~~{});//0
console.log(~~false);//0
console.log(~~true);//1
console.log(~~undefined);//0
console.log(~~null);//0
console.log(~~NaN);//0
复制代码
console.log(~~3.123);//3
console.log(~~(10/3));//3
console.log(~~-3.8);//-3
复制代码

5、>>> 取中间值

  var mid = 1 >>> 1;//0
  var mid = 2 >>> 1;//1
  var mid = 3 >>> 1;//1
  var mid = 4 >>> 1;//2
复制代码

6、|向下取整(相当于Math.floor)

    var a = 12.9 | 0;//12
复制代码

7、处理数组参数为undefined

function test(arr){
    var length = (arr||[]).length;
    console.log(length);
}
test();//0
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值