| 編程(Programming)是編定程序的中文簡稱,就是讓計(jì)算機(jī)代碼解決某個(gè)問題,對某個(gè)計(jì)算體系規(guī)定一定的運(yùn)算方式,使計(jì)算體系按照該計(jì)算方式運(yùn)行,并最終得到相應(yīng)結(jié)果的過程。為了使計(jì)算機(jī)能夠理解(understand)人的意圖,人類就必須將需解決的問題的思路、方法和手段通過計(jì)算機(jī)能夠理解的形式告訴計(jì)算機(jī),使得計(jì)算機(jī)能夠根據(jù)人的指令一步一步去工作,完成某種特定的任務(wù)。這種人和計(jì)算體系之間交流的過程就是編程。 【實(shí)例名稱】 JS代碼制作生日提醒器 【實(shí)例描述】 同學(xué)錄的相關(guān)網(wǎng)頁一般會(huì)顯示最近過生日的同學(xué)姓名,這顯得比較人性化。本例學(xué)習(xí)如何制作這種生日提醒器。 【實(shí)例代碼】 <html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>標(biāo)題頁-本站(www.xue51.com)</title>
<SCRIPT LANGUAGE="JavaScript">
function birthday(year,month,date,person)
//一個(gè)生日對象,包括年、月日和人名
{
this.year=year
this.month=month
this.date=date
this.person=person
}
function personList()
//創(chuàng)建一個(gè)空的列表對象
{ }
pList=new personList()
//創(chuàng)建用戶列表項(xiàng)
pList[0]= new birthday(82,1,16,"張三")
//在列表項(xiàng)中添加生日對象
pList[1]= new birthday(33,9,27,"李四")
pList[2]= new birthday(66,3,1,"王五")
pList[3]= new birthday(79,4,27,"趙六")
pList[4]= new birthday(80,6,2,"小明")
pList[5]= new birthday(50,11,24,"曉紅")
var now=new Date()
//獲取今天的日期
today=new Date(now.getYear(),now.getMonth(),now.getDate())
//設(shè)置一個(gè)對象,一般為年月日0:00:00
function daysFromToday(sdate) {
return Math.round((sdate.getTime()-today.getTime())/(24*60*60*1000))
//返回一個(gè)指定日期距今天的時(shí)間
}
function writeNextBirthday(list)
{
var daysToClosest=366
var closest
for (var i in list)
//遍歷列表中的每一項(xiàng)
{
thisDate=new Date(today.getYear(),list[i].month,list[i].date)
//獲取朋友生日的月日
if (daysFromToday(thisDate)<0)
//如果生日已經(jīng)過了,則計(jì)算到下一年
thisDate.setYear(today.getYear()+1)
if (daysFromToday(thisDate)<daysToClosest) {
daysToClosest=daysFromToday(thisDate)
//計(jì)算距生日的天數(shù)-找出最近的一個(gè)
closest=i
}
}
if (daysToClosest==0)
document.write("<B>今天 "+list[closest].person+" 已經(jīng) "+
(today.getYear()-list[closest].year)+" 歲了 !!!</B><P>")
else if (daysToClosest==1)
document.write("明天 "+list[closest].person+" 即將 "+
(today.getYear()-list[closest].year)+" 歲了!<P>")
else
document.write("最近一個(gè)過生日的是"+
list[closest].person+" 還有 "+daysToClosest+" 天.<P>") }
</SCRIPT>
</head>
<body>
<SCRIPT LANGUAGE="JavaScript">
writeNextBirthday(pList)
//動(dòng)態(tài)輸出最近要過生日的對象
</SCRIPT>
</body>
</html>
【運(yùn)行效果】
 【難點(diǎn)剖析】 本例使用一個(gè)對象數(shù)組包含了所有朋友列表,然后根據(jù)當(dāng)前日期與列表中的月和日進(jìn)行比較,使用“daysToCIosest”變量獲取最近的一個(gè)朋友生日的日期。本例中注意日期的比較和設(shè)置。 【源碼下載】 為了JS代碼的準(zhǔn)確性,請點(diǎn)擊:生日提醒器 進(jìn)行本實(shí)例源碼下載
使用編程語言寫的程序,由于每條指令都對應(yīng)計(jì)算機(jī)一個(gè)特定的基本動(dòng)作,所以程序占用內(nèi)存少、執(zhí)行效率高。 |