一.在网页生成随机数猜数字
<body>
<input type="text" name="result" id="result" value="" />
<input type="button" id="btn" value="猜数字" />
<script type="text/javascript">
//随机输出0-10之间的任意整数
console.log(Math.floor(Math.random()*11))
//猜数字游戏
//随机产生一个0-10之间的任意整数
var num=Math.floor(Math.random()*11)
document.getElementById("btn").onclick=function(){
//获取到文本框中输入的数字
var result=parseInt(document.getElementById("result").value)
if(result>num){
alert("你输入的数字太大了")
} else if(result<num){
alert("你输入的数字太小了")
}else{
alert("恭喜你,猜对了")
}
}
</script>
</body>
二.Math(数学/内置对象)
代码举例:
//Math对象
console.log(Math.ceil(12.3))//返回一个大于该数字的最小整数
console.log(Math.floor(12.3))//返回一个小于该数字的最大整数
console.log(Math.round(12.7))//返回一个四舍五入的整数
console.log(Math.pow(2,3))//返回x的y次幂
console.log(Math.max(2,3,1,4))//返回最大值
三.Date对象(用于处理日期与时间)需要通过new进行实例化
举例:在网页上显示时间日期
<body>
<p id="timer">
</p>
<script type="text/javascript">
//Date对象
//需要通过new进行实例化
//定时器,每个多长时间调用一次回调函数
setInterval(function(){
var time=new Date()//获取的是当前时间
console.log(time)
var year =time.getFullYear()//获取的是年份
var month=time.getMonth()+1//获取的是月份
var date =time.getDate()
var hours=time.getHours()//获取的是小时
var minutes=time.getMinutes()//获取的是分钟
var seconds=time.getSeconds()//获取的是秒数
//拼接0
month=month>9?month:"0"+month
date=date>9?date:"0"+date
hours=hours>9?hours:"0"+hours
minutes=minutes>9?minutes:"0"+minutes
seconds=seconds>9?seconds:"0"+seconds
var result=year+"年"+month+"月"+date+"日"+hours+":"+minutes+":"+seconds
//console.log(result)
document.getElementById("timer").innerHTML=result
},1000)//1000指的是1000毫秒,也就是1秒
setTimeout(function(){
console.log("aa")
},2000)
</script>
</body>
四.花名册随机生成姓名
举例:
<body>
<span id="uname">请点击开始
</span>
<input type="button" id="start" value="开始" />
<input type="button" id="over" value="结束" />
<script type="text/javascript">
var unames=["丁1","丁2","丁3","丁4","丁5"]
var timer
document.getElementById("start").onclick=function(){
timer=setInterval(function(){
//随机产生0-5之间的任意整数
var index=Math.floor(Math.random()*unames.length)
document.getElementById("uname").innerHTML=unames[index]
},100)
}
document.getElementById("over").onclick=function(){
clearInterval(timer)
}
</script>
</body>
五.正则表达式:(限定符)
六.数组
1.数组对象的创建
2.数组下标与数组元素的使用
3.数组的length属性
4.数组元素的遍历
5.数组的常用方法(函数)
举例:
<body>
<script type="text/javascript">
//创建数组
var arr_1=new Array()
console.log(arr_1.length)
//数组中的元素的使用
arr_1[0]="张三"
arr_1[2]="李四"
console.log(arr_1.length)
//创建时指定长度(length)属性
var arr_2=new Array(5)//创建一个数组对象,长度是5
arr_2[0]=10
arr_2[4]=100
arr_2[5]=90
arr_2[6]=40
console.log(arr_2.length)
var arr_3=["张三","李四"]
//arr_3.length=0//清空数组
console.log(arr_3)
//遍历数组中的元素
for(var i in arr_3){
console.log(arr_3[i])
}
for(var i=0;i<arr_3.length;i++){
console.log(arr_3[i])
}
//数组中的常用方法(函数)
var arr_4=["丁1","丁2","丁3","丁4","丁5","丁6"]
arr_4.push("丁7")
arr_4.unshift("丁8")
arr_4.pop()
arr_4.shift()
console.log(arr_4)
//删除数组头和尾之间的任意元素
</script>
</body>
数组的对象: