try异常处理
try异常处理只适用于运行时错误,语法错误try帮不了,逻辑错误任何工具帮不了
try{ //尝试
//尝试执行
}catch(e){ //捕获
// 如果出现异常,执行这里
console.log(e) // e 输出错误对象
}
<body>
<textarea name="name" id="txt1"></textarea>
<button type="button" id="btn1">输出用户列表</button>
<script>
let oBtn=document.getElementById('btn1');
let oTxt=document.getElementById('txt1');
oBtn.onclick=function (){
try {
let arr = JSON.parse(oTxt.value);
console.log(arr);
}catch(e){
alert("数据输入有误");
console.log(e) // e 输出错误对象
}
};
</script>
</body>
JavaScript Math 对象
Math 对象用于执行数学任务。
Math.random() 随机数
// Math.random() 随机数
alert(Math.random()); // 0 , 0.9999999999999... 生成0到1之间的数[0,1]
// random()*n [0,n) 不包括n本身
alert(Math.random()*10); // 0 , 9.999999999999... 乘以10后,最小生成0 最大生成9.99...不会包括10本身
// a+random()*n [a , a+n
alert(8+Math.random()*35); //前面加上8后,最小数可以是(8+0)8,最大数就是(8+ 34.999...)
// 取[9~16]的数
9+random()*7 //最小9 最大(16——9)7
// 取[16~33]的数
16+random()*17
// 取[n~m]的数
n+random()*(m-n)
// 向下取整
Math.floor(3.999999); //3
// 向上取整
Math.ceil(0.000000001); //1
// 四舍五入
Math.round(4.5); //5
Math.round(4.499999); //4
// 随机输出十个3~8之间的数
function rnd(n,m){
return Math.floor(n+Math.random()*(m+1-n));
}
for (let i=0;i<10;i++){
console.log(rnd(3,8));
}