例:
<body>
<span id="result">
</span>
<script type="text/javascript">
//Date new Date()
window.onload=function(){
setInterval(function(){
var time=new Date() //获取的是当前时间
//document.write(time)
var year=time.getFullYear() //年份
var month=time.getMonth()+1 //月份 0-11
var date=time.getDate() //日
var hours=time.getHours() //小时
var minutes=time.getMinutes() //分钟
var seconds=time.getSeconds() //秒数
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
// document.write(result)
document.getElementById("result").innerHTML=result
},1000) //1000毫秒是1秒
}
</script>
</body>
定时器
<span id="uname">
请点击开始
</span>
<input type="button" id="start" value="开始" />
<input type="button" id="end" value="结束" />
<script type="text/javascript">
var uname=["吕佳琪","王宁乐","沈萌","李嘉欣","李停停","侯彤"]
var timer
document.getElementById("start").onclick=function(){
timer=setInterval(function(){
// 产生一个0-5之间的任意整数
var index = Math.floor(Math.random()*uname.length)
document.getElementById("uname").innerHTML=unames[index]
},50)
}
//停止
document.getElementById("end").onclick=function(){
clearInterval(timer) //消除定时器
}
</script>
数组对象
页面加载时执行
window.οnlοad=function(){}
定时器
setInterVal(function(){
},1000)
1000毫秒是一秒,代表定格一秒
清除定时器
chearInterval(定时器名称)
例:
//创建数组
var arr_1=new Array() //没有给数组指定长度
arr_1[0]="张三"
arr_1[3]="李四"
console.log(arr_1.length)
var arr_2=new Array(5) //指定数组的长度
arr_2[6]="王五"
console.log(arr_2.length)
var arr_3=["张三","李四","王五","赵六","小红","小丽"]
//arr_3.length=0 可以清空数组
console.log(arr_3)
//数组中常用的函数
//添加一个元素到数组中
arr_3.push("王浩") //将元素添加到最后面
arr_3.unshift("王浩") //将元素添加到最前面
///删除
arr_3.pop() //将数组中的最后一个元素删除
arr_3.shift()//将数组中的第一个元素删除
arr_3.splice(3,1) //从指定位置删除指定的元素个数
console.log(arr_3)
arr_3.reverse() //反转
console.log(arr_3)
//数组的去重,将不重复的元素放到一个新的数组中
var arr_4=[1,2,3,2,3,4,5,3,2,6,8]
var newArr=[]
for(var i=0;i<arr_4.length;i++){
//判断是否已存在某个元素,如果已存在,则不需要往newArr中添加
if(newArr.indexOf(arr_4[i])==-1){
newArr.push(arr_4[i])
}
}
console.log(newArr)
//多维数组
var citys=new Array();
citys[0] = ["郑州","开封","焦作","商丘"]
citys[1] = ["武汉","天门","黄石","赤壁"]
for(var i=0;i<citys.length;i++){
for (var j = 0;j<citys[i].length;j++) {
console.log(citys[i][j])
}
}
var arr_5=["张三","李四","王五","赵六","小红","小丽"]
var result=arr_5.join("*") //根据指定的字符将数组中的元素拼接成一个字符串
console.log(result)
正则表达式对象
<input type="text" name="pwd" id="pwd" value="" />
<input type="button" name="btn" id="btn" value="验证" />
<script type="text/javascript">
// 密码中只能包含数字、字母、下划线,且长度至少是6位
document.getElementById("btn").onclick=function(){
// 获取文本框中的密码
var pwd=document.getElementById("pwd").value
var reg=/^\w{6,8}$/
//test():返回的结果是一个布尔类型
if(reg.test(pwd)){
alert("验证通过")
}else{
alert("验证失败")
}
}
</script>