JS Math数学计算

Math数学计算
1.最大最小值
max() min()

不支持数组作为参数,只支持多数值参数。因此数组使用…展开语法或者apply方法。

console.log(Math.max(1, 2, 3, 4, 5));
console.log(Math.min(1, 2, 3, 4, 5));
let grade = [12, 3, 5, 67, 88];
console.log(Math.max(grade));
console.log(Math.max(...grade));
console.log(Math.max.apply(null, grade));

在这里插入图片描述

2.向上向下取整
ceil() floor()

不是四舍五入!!!

console.log(Math.ceil(5.4));
console.log(Math.floor(5.99));

在这里插入图片描述

3.舍入函数
toFixed() round()
console.log((5.5666).toFixed(2));
console.log(Math.round(5.5666));

在这里插入图片描述

4.获取随机数
random()

是获取[0,1)的随机数

console.log(Math.random());
5.范围内随机数
(1)[0,5]

Math.floor(Math.random() * (max + 1))

console.log(Math.floor(Math.random() * (5 + 1)));

在这里插入图片描述

(2)[2,5]

min + Math.floor(Math.random() * (max - min + 1))

console.log(2 + Math.floor(Math.random() * (5 - 2 + 1)));

在这里插入图片描述

随机点名
const students = ["alison", "ruby", "andy", "yooo"];
// >=0~<=3
let number = Math.floor(Math.random() * students.length);
console.log(students[number]);
// >=1~<=3
let index = 1 + Math.floor(Math.random() * (students.length - 1));
console.log(students[index]);

function arrayRandomValue(array, start = 0, end) {
    end = end ? end : array.length;
    const index = start + Math.floor(Math.random() * (end - start + 1));
    return array[index];
}
// >=2~<=3
console.log(arrayRandomValue(students, 2, 3));

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值