你还不知道~~这个是什么意思吗,还以为是作者写错了


前言

主要是来学习一下js中运算符的相关的知识


一、来个例子

~~(Math.random() * 10)

看起来像是要获取随机数的。
我们先把括号内的东西粘到控制台看看:

结果:
(Math.random() * 10)
//4.47062635057776
(Math.random() * 10)
//9.485037450706146
(Math.random() * 10)
//1.0411424656363288
(Math.random() * 10)
//5.207778723704015
(Math.random() * 10)
//3.1793270193668133

整体看看结果:
确实是用来获取0到10以内的随机数的

~~(Math.random() * 10)
//5
~~(Math.random() * 10)
//1
~~(Math.random() * 10)
//7
~~(Math.random() * 10)
//6
~~(Math.random() * 10)
//8
~~(Math.random() * 10)
//7
~~(Math.random() * 10)
//1

但是具体的作用是什么呢,还是得到mdn看看。但是并没有搜索到相关符号,只看到了单个的运算符~

二、按位非~

按位非运算符(~)将操作数的位反转。如同其他位运算符一样,它将操作数转化为 32 位的有符号整型。

什么是有符号整型数看这里—>

看看mdn上面提供的例子:

const a = 5;     // 00000000000000000000000000000101
const b = -3;    // 11111111111111111111111111111101

console.log(~a); // 11111111111111111111111111111010
// Expected output: -6

console.log(~b); // 00000000000000000000000000000010
// Expected output: 2

所以能够理解两次取反的意思就是还是原值,但是为什么后面的小数没有了呢。

JavaScript中的浮点数采用的是双精度浮点数类型,即64位的Double类型来表示。IEEE 754标准定义了浮点数二进制表示的规范
按位取反操作符"~~"在转换浮点数时会一次性移除小数部分并通过对整数部分取反、加1来得到整数形式的方法。


三、小知识

字符串转为数字的方法:

const [a, b, c, d, e, f, g, h] = ['1', '2', '3', '4', '5', '6', '7', '8']
console.log(typeof (a - 0), (a - 0))
console.log(typeof parseInt(b), parseInt(b))
console.log(typeof parseFloat(b), parseFloat(b))
console.log(typeof ~~c, ~~c)
console.log(typeof +d, +d)
console.log(typeof Number(e), Number(e))
console.log(typeof Math.floor(f), Math.floor(f))
console.log(typeof Math.round(g), Math.round(g))
console.log(typeof eval(h), eval(h))

结果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43205326/article/details/130527454