javascript向下取整、字符串转数字、四舍五入、变量交换、随机数分布区间、快速排序等的一些使用技巧

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))  //1

console.log(Math.round(0.49))  //0

console.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]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值