1.向下取整
1.1、Math.floor
Math.floor(-45.05); // -46
Math.floor( 45.95); // 45
1.2 、~~ (使用两个非向下取整最方便,运算很快)
例:~~3.14
// 3
例:~~1.1215
// 1
例 ~~Math.E
// 2
2.字符串转数字
2.1、parseFloat:该函数指定字符串中的首个字符是否是数字。如果是,则对字符串进行解析,直到到达数字的末端为止,然后以数字返回该数字,而不是作为字符串。
document.write(parseFloat("11")) document.write(parseFloat("10.00")) document.write(parseFloat("10.33")) document.write(parseFloat("34 45 66")) document.write(parseFloat(" 60 ")) document.write(parseFloat("40 years")) document.write(parseFloat("He was 40"))11 10 10.33 34 60 40 NaN
2.2 、Number() 函数把对象的值转换为数字
var test1= new Boolean(true);console.log(Number(test1));==> 1
3.3、 官方推荐直接用一个加号(+)云算符, 是最快最简洁的,'+'号运算符作为一元运算符时,Expression将进行ToNumber()操作。
// Undefined
+ undefined;
// => NaN
-------------------------------------
// Null
+
null
;
// => 0
-------------------------------------
// Boolean
+
true
;
// => 1
+
false
;
// => 0
-------------------------------------
// String
+
'1'
;
// => 1
+
'-1'
;
// => -1
+
'aaa1'
;
// => NaN
3.四舍五入
3.1、Math.round
console.log(
Math.round(0.50)
) //1console.log(
Math.round(0.49)
) //0console.log(
Math.round(-4.40)
) //-4
3.2、toFixed() 方法可把 Number 四舍五入为指定小数位数的数字
var num = new Number(19.29); document.write (num.toFixed(1)) //19.3+Math.E.toFixed(0)
> 3
+Math.E.toFixed(1)
> 2.7
+Math.E.toFixed(2)
> 2.72
3.3、toPrecision 把数字格式化为指定的长度
var num = new Number(13.3123456789);
var n=num.toPrecision(2);//13
4.最安全的交换变量
let a = 12;
let b = 123;
a = a ^ b;
b = a ^ b;
a = a ^ b;a;
> 123
b;
> 12
5. 获取指定范围内均匀分布的随机数
let x = Math.random() * (max - min) + min;
6.利用sort方法快速排序的时候引入一个随机量
const list = [5, 450 , 1200 , -210 , 22 , 400 , 122205, -8541100];
list.sort(()=>Math.random()-0.5)
(8) [-210, -8541100, 22, 5, 450, 122205, 1200, 400]