js之Math.random()与Math.floor()

本文介绍了JavaScript中的Math.random()用于生成0到1之间(不含1)的随机数,以及Math.floor()用于向下取整的用法。讲解了如何结合这两个函数生成指定范围内的随机整数,包括使用Math.random()乘以特定范围和使用Math.floor()取值的方法。

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

、、、、、、、、、、、仅对以前所学做复习记录使用、、、、、、、、、

Math是一个对象,不是一个构造函数,所以不能new Math

一、返回0到1之间的随机数值,但不包含1,包含零。顾头不顾尾。一般零出现的概率极小,可以忽略不计。
<div class="bg" @click="cssChange"> </div>

cssChange(){					
		console.log(Math.random());
	}

在这里插入图片描述

Math.random()*10的意思:因为random的取值范围是[0,1),所以0x10=0,1x10=10;取的是0-10之间的数字。

在这里插入图片描述

二、Math.floor()是向下取整数(向越小的值方向取值),即将小数点后面的数字全部省去;如果是个整数就取它本身的值:
// 向越小的值方向取值
Math.floor(1.222)       // 1
Math.floor(1.9999999)  // 1
Math.floor(1)          // 1
Math.floor(-1)        // -1
Math.floor(-1.222)    // -2
三、获取x到y的随机整数,包含xy,用Math.round(),公式:

Math.round(Math.random()*(y-x)+x);

例如获取0-10

<div class="bg" @click="cssChange"> </div>

cssChange(){					
		console.log(Math.round(Math.random()*(10-0)+0));
		
	}

在这里插入图片描述

四、用Math.floor()取x到y的值,包含xy,公式:

Math.floor(y+1-Math.random()*(y+1-x))

例如:取5-7

methods:{
				cssChange(){										
					console.log(Math.floor(8-Math.random()*(8-5)));
				}
			}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值