每一項(xiàng)都是js中的小技巧,但十分的實(shí)用!
1.document.write(""); 輸出語(yǔ)句
2.JS中的注釋為//
3.傳統(tǒng)的HTML文檔順序是:document->html->(head,body)
4.一個(gè)瀏覽器窗口中的DOM順序是:window->(navigator,screen,history,location,document)
5.得到表單中元素的名稱(chēng)和值:document.getElementById("表單中元素的ID號(hào)").name(或value)
6.一個(gè)小寫(xiě)轉(zhuǎn)大寫(xiě)的JS: document.getElementById("output").value = document.getElementById("i
nput").value.toUpperCase();
7.JS中的值類(lèi)型:String,Number,Boolean,Null,Object,Function
8.JS中的字符型轉(zhuǎn)換成數(shù)值型:parseInt(),parseFloat()
9.JS中的數(shù)字轉(zhuǎn)換成字符型:(""+變量)
10.JS中的取字符串長(zhǎng)度是:(length)
11.JS中的字符與字符相連接使用+號(hào).
12.JS中的比較操作符有:==等于,!=不等于,>,>=,<.<=
13.JS中聲明變量使用:var來(lái)進(jìn)行聲明
14.JS中的判斷語(yǔ)句結(jié)構(gòu):if(condition){}else{}
15.JS中的循環(huán)結(jié)構(gòu):for([initial e-xpression];[condition];[upadte e-xpression]) {inside loop}
16.循環(huán)中止的命令是:break
17.JS中的函數(shù)定義:function functionName([parameter],...)
18.當(dāng)文件中出現(xiàn)多個(gè)form表單時(shí).可以用document.forms[0],document.forms[1]來(lái)代替.
19.窗口:打開(kāi)窗口window.open(), 關(guān)閉一個(gè)窗口:window.close(), 窗口本身:self
20.狀態(tài)欄的設(shè)置:window.status="字符";
21.彈出提示信息:window.alert("字符");
22.彈出確認(rèn)框:window.confirm();
23.彈出輸入提示框:window.prompt();
24.指定當(dāng)前顯示鏈接的位置:window.location.href="URL"
25.取出窗體中的所有表單的數(shù)量:document.forms.length
26.關(guān)閉文檔的輸出流:document.close();
27.字符串追加連接符:+=
28.創(chuàng)建一個(gè)文檔元素:document.createElement(),document.createTextNode()
29.得到元素的方法:document.getElementById()
30.設(shè)置表單中所有文本型的成員的值為空:
var form = window.document.forms[0]
for (var i = 0; i if (form.elements.type == "text"){
form.elements.value = "";
}
}
31.復(fù)選按鈕在JS中判斷是否選中:document.forms[0].checkThis.checked (checked屬性代表為是否選中
返回TRUE或FALSE)
32.單選按鈕組(單選按鈕的名稱(chēng)必須相同):取單選按鈕組的長(zhǎng)度document.forms[0].groupName.length
33.單選按鈕組判斷是否被選中也是用checked.
34.下拉列表框的值:document.forms[0].selectName.options[n].value (n有時(shí)用下拉列表框名稱(chēng)加上.sel
ectedIndex來(lái)確定被選中的值)
35.字符串的定義:var myString = new String("This is lightsword");
36.字符串轉(zhuǎn)成大寫(xiě):string.toUpperCase(); 字符串轉(zhuǎn)成小寫(xiě):string.toLowerCase();
37.返回字符串2在字符串1中出現(xiàn)的位置:String1.indexOf("String2")!=-1則說(shuō)明沒(méi)找到.
38.取字符串中指定位置的一個(gè)字符:StringA.charAt(9);
39.取出字符串中指定起點(diǎn)和終點(diǎn)的子字符串:stringA.substring(2,6);
40.數(shù)學(xué)函數(shù):Math.PI(返回圓周率),Math.SQRT2(返回開(kāi)方),Math.max(value1,value2)返回兩個(gè)數(shù)中的最
在值,Math.pow(value1,10)返回value1的十次方,Math.round(value1)四舍五入函數(shù),Math.floor(Math.ra
ndom()*(n+1))返回隨機(jī)數(shù)
41.定義日期型變量:var today = new Date();
42.日期函數(shù)列表:dateObj.getTime()得到時(shí)間,dateObj.getYear()得到年份,dateObj.getFullYear()得到
四位的年份,dateObj.getMonth()得到月份,dateObj.getDate()得到日,dateObj.getDay()得到日期幾,dat
eObj.getHours()得到小時(shí),dateObj.getMinutes()得到分,dateObj.getSeconds()得到秒,dateObj.setTi
me(value)設(shè)置時(shí)間,dateObj.setYear(val)設(shè)置年,dateObj.setMonth(val)設(shè)置月,dateObj.setDate(va
l)設(shè)置日,dateObj.setDay(val)設(shè)置星期幾,dateObj.setHours設(shè)置小時(shí),dateObj.setMinutes(val)設(shè)置分,
dateObj.setSeconds(val)設(shè)置秒 [注意:此日期時(shí)間從0開(kāi)始計(jì)]
43.FRAME的表示方式: [window.]frames[n].ObjFuncVarName,frames["frameName"].ObjFuncVarN
ame,frameName.ObjFuncVarName
44.parent代表父親對(duì)象,top代表最頂端對(duì)象
45.打開(kāi)子窗口的父窗口為:opener
46.表示當(dāng)前所屬的位置:this
47.當(dāng)在超鏈接中調(diào)用JS函數(shù)時(shí)用:(javascript :)來(lái)開(kāi)頭后面加函數(shù)名
48.在老的瀏覽器中不執(zhí)行此JS:
49.引用一個(gè)文件式的JS:
50.指定在不支持腳本的瀏覽器顯示的HTML:
51.當(dāng)超鏈和onCLICK事件都有時(shí),則老版本的瀏覽器轉(zhuǎn)向a.html,否則轉(zhuǎn)向b.html.例:dfsadf
52.JS的內(nèi)建對(duì)象有:Array,Boolean,Date,Error,EvalError,Function,Math,Number,Object,RangeError,
ReferenceError,RegExp,String,SyntaxError,TypeError,URIError
53.JS中的換行:\n
54.窗口全屏大小:
55.JS中的all代表其下層的全部元素
56.JS中的焦點(diǎn)順序:document.getElementByid("表單元素").tabIndex = 1
57.innerHTML的值是表單元素的值:如
"how are you"
,則innerHTML的值就是:how are you
58.innerTEXT的值和上面的一樣,只不過(guò)不會(huì)把這種標(biāo)記顯示出來(lái).
59.contentEditable可設(shè)置元素是否可被修改,isContentEditable返回是否可修改的狀態(tài).
60.isDisabled判斷是否為禁止?fàn)顟B(tài).disabled設(shè)置禁止?fàn)顟B(tài)
61.length取得長(zhǎng)度,返回整型數(shù)值
62.addBehavior()是一種JS調(diào)用的外部函數(shù)文件其擴(kuò)展名為.htc
63.window.focus()使當(dāng)前的窗口在所有窗口之前.
64.blur()指失去焦點(diǎn).與FOCUS()相反.
65.select()指元素為選中狀態(tài).
66.防止用戶(hù)對(duì)文本框中輸入文本:onfocus="this.blur()"
67.取出該元素在頁(yè)面中出現(xiàn)的數(shù)量:document.all.tags("div(或其它HTML標(biāo)記符)").length
68.JS中分為兩種窗體輸出:模態(tài)和非模態(tài).window.showModaldialog(),window.showModeless()
69.狀態(tài)欄文字的設(shè)置:window.status='文字',默認(rèn)的狀態(tài)欄文字設(shè)置:window.defaultStatus = '文字.';
70.添加到收藏夾:external.AddFavorite("
http://www.dannyg.com"t;,"jaskdlf");
71.JS中遇到腳本錯(cuò)誤時(shí)不做任何操作:window.onerror = doNothing; 指定錯(cuò)誤句柄的語(yǔ)法為:window.on
error = handleError;
72.JS中指定當(dāng)前打開(kāi)窗口的父窗口:window.opener,支持opener.opener...的多重繼續(xù).
73.JS中的self指的是當(dāng)前的窗口
74.JS中狀態(tài)欄顯示內(nèi)容:window.status="內(nèi)容"
75.JS中的top指的是框架集中最頂層的框架
76.JS中關(guān)閉當(dāng)前的窗口:window.close();
77.JS中提出是否確認(rèn)的框:if(confirm("Are you sure?"))else{alert("Not Ok");}
78.JS中的窗口重定向:window.navigate("
http://www.sina.com.cn"t;);
79.JS中的打印:window.print()
80.JS中的提示輸入框:window.prompt("message","defaultReply");
81.JS中的窗口滾動(dòng)條:window.scroll(x,y)
82.JS中的窗口滾動(dòng)到位置:window.scrollby
83.JS中設(shè)置時(shí)間間隔:setInterval("expr",msecDelay)或setInterval(funcRef,msecDelay)或setTimeou
t
84.JS中的模態(tài)顯示在IE4+行,在NN中不行:showModalDialog("URL"[,arguments][,features]);
85.JS中的退出之前使用的句柄:function verifyClose(){event.returnValue="we really like you and ho
pe you will stay longer.";}} window.onbeforeunload=verifyClose;
86.當(dāng)窗體第一次調(diào)用時(shí)使用的文件句柄:onload()
87.當(dāng)窗體關(guān)閉時(shí)調(diào)用的文件句柄:onunload()
88.window.location的屬性: protocol(http:),hostname(example.com),port(80),host(e
xample.com:80),pathname("/a/a.html"),hash("#giantGizmo",指跳轉(zhuǎn)到相應(yīng)的錨記),href(全部的信
息)
89.window.location.reload()刷新當(dāng)前頁(yè)面.
90.window.history.back()返回上一頁(yè),window.history.forward()返回下一頁(yè),window.history.go(返回
第幾頁(yè),也可以使用訪問(wèn)過(guò)的URL)
91.document.write()不換行的輸出,document.writeln()換行輸出
92.document.body.noWrap=true;防止鏈接文字折行.
93.變量名.charAt(第幾位),取該變量的第幾位的字符.
94."abc".charCodeAt(第幾個(gè)),返回第幾個(gè)字符的ASCii碼值.
95.字符串連接:string.concat(string2),或用+=進(jìn)行連接
96.變量.indexOf("字符",起始位置),返回第一個(gè)出現(xiàn)的位置(從0開(kāi)始計(jì)算)
97.string.lastIndexOf(searchString[,startIndex])最后一次出現(xiàn)的位置.
98.string.match(regExpression),判斷字符是否匹配.
99.string.replace(regExpression,replaceString)替換現(xiàn)有字符串.
100.string.split(分隔符)返回一個(gè)數(shù)組存儲(chǔ)值.
101.string.substr(start[,length])取從第幾位到指定長(zhǎng)度的字符串.
102.string.toLowerCase()使字符串全部變?yōu)樾?xiě).
103.string.toUpperCase()使全部字符變?yōu)榇髮?xiě).
104.parseInt(string[,radix(代表進(jìn)制)])強(qiáng)制轉(zhuǎn)換成整型.
105.parseFloat(string[,radix])強(qiáng)制轉(zhuǎn)換成浮點(diǎn)型.
106.isNaN(變量):測(cè)試是否為數(shù)值型.
107.定義常量的關(guān)鍵字:const,定義變量的關(guān)鍵字:var
--------------------------------------------------------------------------------------------------------------------------------
javascript38種小技巧,推薦新手查看。
事件源對(duì)象
event.srcElement.tagName
event.srcElement.type
捕獲釋放
event.srcElement.setCapture();
event.srcElement.releaseCapture();
事件按鍵
event.keyCode
event.shiftKey
event.altKey
event.ctrlKey
事件返回值
event.returnValue
鼠標(biāo)位置
event.x
event.y
窗體活動(dòng)元素
document.activeElement
綁定事件
document.captureEvents(Event.KEYDOWN);
訪問(wèn)窗體元素
document.all("txt").focus();
document.all("txt").select();
窗體命令
document.execCommand
窗體COOKIE
document.cookie
菜單事件
document.oncontextmenu
創(chuàng)建元素
document.createElement("SPAN");
根據(jù)鼠標(biāo)獲得元素:
document.elementFromPoint(event.x,event.y).tagName=="TD
document.elementFromPoint(event.x,event.y).appendChild(ms)
窗體圖片
document.images[索引]
窗體事件綁定
document.onmousedown=scrollwindow;
元素
document.窗體.elements[索引]
對(duì)象綁定事件
document.all.xxx.detachEvent('onclick',a);
插件數(shù)目
navigator.plugins
取變量類(lèi)型
typeof($js_libpath) == "undefined"
下拉框
下拉框.options[索引]
下拉框.options.length
查找對(duì)象
document.getElementsByName("r1");
document.getElementById(id);
定時(shí)
timer=setInterval('scrollwindow()',delay);
clearInterval(timer);
UNCODE編碼
escape() ,unescape
父對(duì)象
obj.parentElement(dhtml)
obj.parentNode(dom)
交換表的行
TableID.moveRow(2,1) document.all.csss.href = "a.css";
替換CSS
并排顯示
display:inline
隱藏焦點(diǎn)
hidefocus=true
根據(jù)寬度換行
style="word-break:break-all"
自動(dòng)刷新
<meta HTTP-EQUIV="refresh" CONTENT="8;URL=http://c98.yeah.net">
簡(jiǎn)單郵件
<a href="mailto:aaa@bbb.com?subject=ccc&body=xxxyyy">
快速轉(zhuǎn)到位置
obj.scrollIntoView(true)
錨
<a name="first">
<a href="#first">anchors</a>
網(wǎng)頁(yè)傳遞參數(shù)
location.search();
可編輯
obj.contenteditable=true
執(zhí)行菜單命令
obj.execCommand
雙字節(jié)字符
/[^\x00-\xff]/
漢字
/[\u4e00-\u9fa5]/
讓英文字符串超出表格寬度自動(dòng)換行
word-wrap: break-word; word-break: break-all;
透明背景
<IFRAME src="1.htm" width=300 height=180 allowtransparency></iframe>
獲得style內(nèi)容
obj.style.cssText
HTML標(biāo)簽
document.documentElement.innerHTML
第一個(gè)style標(biāo)簽
document.styleSheets[0]
style標(biāo)簽里的第一個(gè)樣式
document.styleSheets[0].rules[0]
防止點(diǎn)擊空鏈接時(shí),頁(yè)面往往重置到頁(yè)首端。
<a href="javascript:function()">word</a>
上一網(wǎng)頁(yè)源
asp:
request.servervariables("HTTP_REFERER")
javascript:
document.referrer
釋放內(nèi)存
CollectGarbage();
禁止右鍵
document.oncontextmenu = function() { return false;}
禁止保存
<noscript><iframe src="*.htm"></iframe></noscript>
禁止選取<body oncontextmenu="return false" ondragstart="return false" onselectstart ="return false" onselect="document.selection.empty()" oncopy="document.selection.empty()" onbeforecopy="return false"onmouseup="document.selection.empty()>
禁止粘貼
<input type=text onpaste="return false">
地址欄圖標(biāo)
<link rel="Shortcut Icon" href="favicon.ico">
favicon.ico 名字最好不變16*16的16色,放虛擬目錄根目錄下
收藏欄圖標(biāo)
<link rel="Bookmark" href="favicon.ico">
查看源碼
<input type=button value=查看網(wǎng)頁(yè)源代碼 onclick="window.location = 'view-source:'+ '
http://www.csdn.net/'">
關(guān)閉輸入法
<input style="ime-mode:disabled">
自動(dòng)全選
<input type=text name=text1 value="123" onfocus="this.select()">
ENTER鍵可以讓光標(biāo)移到下一個(gè)輸入框
<input onkeydown="if(event.keyCode==13)event.keyCode=9">
文本框的默認(rèn)值
<input type=text value="123" onfocus="alert(this.defaultValue)">
title換行
obj.title = "123 sdfs "
獲得時(shí)間所代表的微秒
var n1 = new Date("2004-10-10".replace(/-/g, "\/")).getTime()
窗口是否關(guān)閉
win.closed
checkbox扁平
<input type=checkbox style="position: absolute; clip:rect(5px 15px 15px 5px)"><br>
獲取選中內(nèi)容
document.selection.createRange().duplicate().text
自動(dòng)完成功能
<input type=text autocomplete=on>打開(kāi)該功能
<input type=text autocomplete=off>關(guān)閉該功能
窗口最大化
<body onload="window.resizeTo(window.screen.width - 4,window.screen.height-50);window.moveTo(-4,-4)">
無(wú)關(guān)閉按鈕IE
window.open("aa.htm", "meizz", "fullscreen=7");
統(tǒng)一編碼/解碼
alert(decodeURIComponent(encodeURIComponent("
http://你好.com?as= hehe")))
encodeURIComponent對(duì)":"、"/"、";" 和 "?"也編碼
表格行指示
<tr onmouseover="this.bgColor='#f0f0f0'" onmouseout="this.bgColor='#ffffff'">
------------------------------------------------------------------------------------------------------------------------------------------------
核心(Core) Javascript 學(xué)習(xí)手記
核心(Core) Javascript 學(xué)習(xí)手記
linenum
CreateD BY STABX, AT 2006-9-5.
Javascript Notes By shawl.qiu
---/-------------------------------------------------------------
-3.1 函數(shù)比其他代碼優(yōu)先執(zhí)行
-3. 優(yōu)先級(jí)
-2.4 同時(shí)初始化多個(gè)變量并賦相同值
-2.3 在函數(shù)中使用 var 定義一個(gè)變量, 該變量將影響整個(gè)函數(shù), 不分先后.
-2.2 全局變量與局部變量
-2.1.2 普通定義變量 2
-2.1.1 普通定義變量 1
-2.1 普通定義變量
-2. var 定義變量
-1.5 in 操作符
-1.4.2 true 等價(jià) 1, false 等價(jià) 0.
-1.4 == 與 ===
-1.4.1 NaN
-1.3 0/0=?
-1.2 類(lèi)型轉(zhuǎn)換
-1.1 -- 與 ++
-1.1.1
-1. 運(yùn)算符
0. 語(yǔ)法
0.1 Switch
1. 按鈕
1.1 前進(jìn)后退按鈕
1.2 確認(rèn)按鈕
1.3 最原始也最實(shí)用的 UBB 代碼輸入方法——SCRIPT & FORM
1.4 Prompt
1.5.1 鼠標(biāo)經(jīng)過(guò)時(shí)選中,并隱藏原框的文字, 移開(kāi)再顯示文字 ——文本框
1.5 鼠標(biāo)經(jīng)過(guò)時(shí)選中 ——復(fù)選框 Focus()
1.6 鼠標(biāo)經(jīng)過(guò)自動(dòng)提交表單
2. 接收鍵盤(pán)事件
2.1 按任何鍵關(guān)閉窗口
2.2 實(shí)時(shí)顯示更改的圖片鏈接
3. 數(shù)組/Array
3.1 Javascript 結(jié)合 Asp 使用數(shù)組
4. 控制圖片大小
5. 雙擊拷貝文本
6. IE 全屏顯示
7. 文本框回車(chē)鏈接
8. 顯示頁(yè)面所有元素
9. 正則表達(dá)式
10. 接收鼠標(biāo)事件
10.1 單擊鼠標(biāo)右擊關(guān)閉窗口 (我用左手)
10.2 鼠標(biāo)移過(guò)選擇表單項(xiàng)
11. 字符串
11.1 檢測(cè)字符串中是否出現(xiàn)某字符
12. 隨機(jī)數(shù)
12.1.1 生成 GUID 2
12.1 生成 GUID
13. 時(shí)間操作
13.1 以毫秒為單位的倒計(jì)時(shí)跳轉(zhuǎn), 來(lái)源 CSDN
14. switch
14.1 簡(jiǎn)單 switch
15 if 判斷
15.1.2 簡(jiǎn)單 if 判斷 3
15.1.1 簡(jiǎn)單 if 判斷 2
15.1 簡(jiǎn)單 if 判斷
15.2 if 判斷的 三個(gè) 寫(xiě)法
15.3 判斷執(zhí)行文件使用網(wǎng)絡(luò)還是使用本地協(xié)議
15.4 if...else 寫(xiě)法
16. 簡(jiǎn)單 while
16. while
17. do while
17.1.2 簡(jiǎn)單 do while
17.1 簡(jiǎn)單 do while
18. for
18.1 簡(jiǎn)單 for
18.2 簡(jiǎn)單 for 1
18.3 循環(huán)列出從 a - z 的字母
18.3 n階乘
18.4 Fibonacci Numbers
19. for in
19.1.1 簡(jiǎn)單 for in 1
19.1 簡(jiǎn)單 for in
19.2.1 for in 賦值 [數(shù)組] 1
19.2 for in 賦值 [數(shù)組]
20. try, catch, finally
20.1.1 簡(jiǎn)單 try, catch 1
20.1 簡(jiǎn)單 try, catch
21. with
21.1 簡(jiǎn)單with (另一寫(xiě)法)
21.1 簡(jiǎn)單 with
22. break, continue
22.1 continue
22.2.1 break 標(biāo)簽
22.2 break
23. call, apply
23.1.1 找出數(shù)組中最大的數(shù)
23.1 apply
24. object
24.1.1 創(chuàng)建簡(jiǎn)單對(duì)象 一
24.1.2 創(chuàng)建簡(jiǎn)單對(duì)象 二
24.1 創(chuàng)建簡(jiǎn)單對(duì)象
24.2.1 創(chuàng)建嵌套對(duì)象 1
24.2 創(chuàng)建嵌套對(duì)象
24.3 刪除對(duì)象中的屬性
24.4.1 遍歷對(duì)象中的屬性名 1
24.4 遍歷對(duì)象中的屬性名
24.5 obj.propertyIsEnumerable('ele')
24.6 obj.hasOwnProperty('ele')
25. toString
25.1 使用 toString 列出數(shù)組中的元素
26. Array()
26.0.1 簡(jiǎn)單創(chuàng)建數(shù)組, 并賦值 2
26.0 簡(jiǎn)單創(chuàng)建數(shù)組, 并賦值
26.0.3 創(chuàng)建數(shù)組中的數(shù)組
26.0.4 創(chuàng)建數(shù)組中的對(duì)象
26.0.2 簡(jiǎn)單創(chuàng)建數(shù)組
26.1 [array].push(), [array].pop()
26.2 數(shù)組排序
26.3 創(chuàng)建數(shù)組指定維數(shù), 從 1 開(kāi)始.
27. RegExp
27.1 普通操作 1
27.2 test 語(yǔ)句
27.3 exec 語(yǔ)句
28. new 語(yǔ)法
29. isNaN
30. Date()
30.1 輸出年月日, 時(shí)分秒 的日期格式
31. function 函數(shù)
31.1.1.1 三種定義函數(shù)的方法 1.1
31.10 在數(shù)組中存儲(chǔ)函數(shù), 并引用
31.1.1 三種定義函數(shù)的方法 1
31.1.2 三種定義函數(shù)的方法 2
31.1 三種定義函數(shù)的方法
31.2 在標(biāo)簽中寫(xiě)函數(shù)
31.3 創(chuàng)建嵌套函數(shù)
31.4.1 創(chuàng)建遞歸函數(shù) 1
31.4 創(chuàng)建遞歸函數(shù)
31.5 創(chuàng)建 函數(shù)對(duì)象
31.6 在函數(shù)內(nèi)部定義的函數(shù)只能在該函數(shù)內(nèi)部調(diào)用
31.7 定義函數(shù)變量, 并賦值
31.8 變量引用函數(shù)
31.9 在對(duì)象中存儲(chǔ)函數(shù), 并引用
31.11 function.call()
31.12 在函數(shù)內(nèi)定義的變量可以被下級(jí)內(nèi)嵌函數(shù)調(diào)用
32. typeof 查看數(shù)據(jù)類(lèi)型
32.1
33. obj.valueOf() 返回原始值
34. Math 對(duì)象
34.1.1 生成 1 至 4 的隨機(jī)數(shù)
34.1 Math.random();
34.2 求 x 的 n 次方
35. delete
36. confirm() 確認(rèn)框
36.1 帶條件確認(rèn)框
37. window.open
37. window
37.1 打開(kāi)沒(méi)有焦點(diǎn)的窗口
38. return 返回值
38.1 return true
38.2 return undefined
39. throw
39.1 簡(jiǎn)單產(chǎn)生錯(cuò)誤
40. arguments
40.1 判斷 arguments.length
40.2 列出所有 argument 的值
40.3 arguments.callee / 調(diào)用函數(shù)本身
41. .to******
41.1 toString
42. parseInt() / parseFolat()
--------------------------------
42. parseInt() / parseFolat()
<script type="text/javascript">
//<![CDATA[
var str='1.1322 this test ';
document.write(('str like this: ').bold()+str.fontcolor('red')+'<br/>');
document.write(('parseInt(str): ').bold()+parseInt(str)+'<br/>');
document.write(('parseFloat(str): ').bold()+parseFloat(str)+'<br/>');
document.write(('parseInt(1111,2): ').bold()+parseInt(1111,2)+'<br/>');
document.write(('parseInt(1111,8): ').bold()+parseInt(1111,8)+'<br/>');
document.write(('parseInt(1111): ').bold()+parseInt(1111)+'<br/>');
document.write(('parseInt(1111,16): ').bold()+parseInt(1111,16)+'<br/>');
//]]>
</script>
41. .to******
<script type="text/javascript">
//<![CDATA[
var num=12345.6789
document.write(('parseInt(num): ').bold()+parseInt(num)+'<br/>');
document.write(('num.toFixed(0): ').bold()+num.toFixed(0)+'<br/>');
document.write(('num.toFixed(2): ').bold()+num.toFixed(2)+'<br/>');
document.write(('num.toExponential(2): ').bold()+num.toExponential(2)+'<br/>');
document.write(('num.toExponential(1): ').bold()+num.toExponential(1)+'<br/>');
document.write(('num.toPrecision(1): ').bold()+num.toPrecision(1)+'<br/>');
document.write(('num.toPrecision(2): ').bold()+num.toPrecision(2)+'<br/>');
//]]>
</script>
41.1 toString
<script type="text/javascript">
//<![CDATA[
var num=123456789
document.write(('num.toString(): ').bold()+num.toString()+'<br/>');
document.write(('num.toString(2): ').bold()+num.toString(2)+'<br/>');
document.write(("'0'+num.toString(8): ").bold()+'0'+num.toString(8)+'<br/>');
document.write(("'0x'+num.toString(16): ").bold()+'0x'+num.toString(16)+'<br/>');
//]]>
</script>
40. arguments
40.1 判斷 arguments.length
<script type="text/javascript">
//<![CDATA[
function t(a, b, c, d){
if(arguments.length!=4)document.write(('error! argument must be 4 element.').fontcolor('red')+' current arguments length: '+arguments.length+'<br/>');
else document.write(('this right: '+arguments.length).bold()+' arguments<br/>');
}
t();
t('a', 'b', 'c', 'd');
t('a', 'b', 'c', 'd', 'e');
//]]>
</script>
40.2 列出所有 argument 的值
<script type="text/javascript">
//<![CDATA[
function t(){
for(var i=0; i<arguments.length; i++){
document.write(('arguments['+i+']').bold()+' = '+arguments[i].fontcolor('red')+'<br/>');
}
}
var temp='test';
t('aaa', 'bbb', 'ccc', 'ddd', 'eee', temp);
//]]>
</script>
40.3 arguments.callee / 調(diào)用函數(shù)本身
<script type="text/javascript">
//<![CDATA[
var t=function(x){
document.write(x+'<br/>');
if(x>1){
arguments.callee(x-1);
}
}
t(10);
//]]>
</script>
39. throw
39.1 簡(jiǎn)單產(chǎn)生錯(cuò)誤
<script type="text/javascript">
//<![CDATA[
t(10);
t();
function t(x){
if(typeof x==='undefined')throw new Error('x must be own a value');
document.write(x);
}
//]]>
</script>
38. return 返回值
38.1 return true
<script type="text/javascript">
//<![CDATA[
function t(ipt){
window.status=ipt;
return true;
}
t('test this');
//]]>
</script>
38.2 return undefined
<script type="text/javascript">
//<![CDATA[
function t(t){
if(t==null)return;
}
document.write(t()); // undefined
//]]>
</script>
37. window
37. window.open
37.1 打開(kāi)沒(méi)有焦點(diǎn)的窗口
<script type="text/javascript">
//<![CDATA[
var w=window.open('/')
w.blur();
window.focus();
//]]>
</script>
36. confirm() 確認(rèn)框
36.1 帶條件確認(rèn)框
<script type="text/javascript">
//<![CDATA[
var x=confirm('what doing with you')
if(x){alert('ok')}else alert('good choice');
//]]>
</script>
35. delete
<script type="text/javascript">
//<![CDATA[
var t={i:'ok', j:'ok too'}
document.write(delete t.i); // true
document.write('<br/>');
document.write(delete t); // false 不能刪除 使用 var 定義的變量或?qū)ο?
document.write('<br/>');
document.write(delete n); // true 刪除不存在的元素.
document.write('<br/>');
document.write(delete j); // true
document.write('<br/>');
//]]>
</script>
34. Math 對(duì)象
34.1 Math.random();
34.1.1 生成 1 至 4 的隨機(jī)數(shù)
<script type="text/javascript">
//<![CDATA[
document.write(parseInt(Math.random()*4+1)+'<br/>');
//]]>
</script>
34.2 求 x 的 n 次方
<script type="text/javascript">
//<![CDATA[
document.write(Math.pow(2,10));
//]]>
</script>
33. obj.valueOf() 返回原始值
<script type="text/javascript">
//<![CDATA[
var a=1, b='test', c=false, d=new Object();
document.write(a.valueOf()+'<br/>'); // 1
document.write(b.valueOf()+'<br/>'); // test
document.write(c.valueOf()+'<br/>'); // false
document.write(d.valueOf()+'<br/>'); // [object Object]
//]]>
</script>
32. typeof 查看數(shù)據(jù)類(lèi)型
<script type="text/javascript">
//<![CDATA[
var a=['a', 'b', 'c']
document.write(typeof a); // object
document.write(a.valueOf()); // a, b, c
document.write(typeof null); // object
//]]>
</script>
32.1
<script type="text/javascript">
//<![CDATA[
var a=['a', 'b', 'c']
document.write(typeof a); // object
document.write(a.valueOf()); // a, b, c
//]]>
</script>
31. function 函數(shù)
31.1 三種定義函數(shù)的方法
<script type="text/javascript">
//<![CDATA[
function f(){ alert('function f');};
var f1=function(){ alert('function f1');};
var f2=new Function('', "alert('function f2')");
f(); f1(); f2();
//]]>
</script>
31.1.1 三種定義函數(shù)的方法 1
<script type="text/javascript">
//<![CDATA[
var t=new Function('a', 'b', 'return a+b;')
document.write(t('ok ', 'test this'));
//]]>
</script>
31.1.1.1 三種定義函數(shù)的方法 1.1
<script type="text/javascript">
//<![CDATA[
var t=new Function("return 'test this'")
document.write(t());
//]]>
</script>
31.1.2 三種定義函數(shù)的方法 2
<script type="text/javascript">
//<![CDATA[
var t=function(str){return 'this test'+str};
document.write(t(', right.'));
//]]>
</script>
31.2 在標(biāo)簽中寫(xiě)函數(shù)
<div onclick="javascript:var go=function(){alert(111)};go();">div 可用</div>
<div onclick="go()">div1 不可用</div>
<div onclick="javascript:( function(){alert(111);} )()">div2 可用</div>
<div onclick="javascript:function go(){alert(111);}go();">div3 可用</div>
31.3 創(chuàng)建嵌套函數(shù)
<script type="text/javascript">
//<![CDATA[
function level1(){
var lNm='level 1'
document.write(lNm+'<br/>');
function level2(){
var lNm='level 2'
document.write(lNm+'<br/>');
}
level2();
}
level1();
//]]>
</script>
31.4 創(chuàng)建遞歸函數(shù)
<%
var i=0;
function t(){
i++;
if(i<100){
Response.Write(i+'<br/>');
return t();
}
Response.Write(i+'<br/>');
}
t();
%>
31.4.1 創(chuàng)建遞歸函數(shù) 1
<script type="text/javascript">
//<![CDATA[
function fctr(n){
if(n<=1)return 1;
return n*fctr(n-1);
}
document.write(fctr(4));
//]]>
</script>
31.5 創(chuàng)建 函數(shù)對(duì)象
<script type="text/javascript">
//<![CDATA[
function fT(){
this.title='o test';
this.subtitle=fTt();
function fTt(){
return 'o subtitle';
}
}
var t=new fT();
document.write(t.title+'<br/>');
document.write(t.subtitle+'<br/>');
t=null;
//]]>
</script>
31.6 在函數(shù)內(nèi)部定義的函數(shù)只能在該函數(shù)內(nèi)部調(diào)用
<script type="text/javascript">
//<![CDATA[
function lev1(){
document.write('lev 1<br/>');
function lev2(){
document.write('lev 2<br/>');
}
lev2();
}
lev1();
lev2(); // 出錯(cuò), 在函數(shù)內(nèi)部定義的函數(shù)只能在該函數(shù)內(nèi)部調(diào)用
//]]>
</script>
31.7 定義函數(shù)變量, 并賦值
<script type="text/javascript">
//<![CDATA[
var t=(function(str){return str+str+'<br/>';})('test this ')
document.write(t);
//]]>
</script>
31.8 變量引用函數(shù)
<script type="text/javascript">
//<![CDATA[
function t(x){
x+='';
return x+x;
}
document.write(t('how fun ')+'<br>'); // how fun how fun
var u=t // u 引用 函數(shù) t
document.write(u('how fun too ')+'<br>'); // how fun too how fun too
//]]>
</script>
31.9 在對(duì)象中存儲(chǔ)函數(shù), 并引用
<script type="text/javascript">
//<![CDATA[
var o=new Object();
o.t=function(x){x+=''; return x+x;}
var t=o.t('test this ');
document.write(t);
//]]>
</script>
31.10 在數(shù)組中存儲(chǔ)函數(shù), 并引用
<script type="text/javascript">
//<![CDATA[
var a=new Array(3);
a[0]=function(x){x+='';return x+x};
a[1]='test this ';
a[2]=a[0](a[1]);
document.write(a[2]);
//]]>
</script>
31.11 function.call()
<script type="text/javascript">
//<![CDATA[
var o=new Object();
function f(a, b){
return a+b
}
document.write(f.call(o, 1, 2));
//]]>
</script>
31.12 在函數(shù)內(nèi)定義的變量可以被下級(jí)內(nèi)嵌函數(shù)調(diào)用
<script type="text/javascript">
//<![CDATA[
function t(){
var x=" this's test ";
function u(){
document.write(x.bold());
}
u();
}
t();
//]]>
</script>
30. Date()
30.1 輸出年月日, 時(shí)分秒 的日期格式
<script type="text/javascript">
//<![CDATA[
var $dt=new Date();
document.write('yyyy-nn-dd: '+$dt.toLocaleDateString()+'<br/>');
document.write('hh-mm-ss: '+$dt.toLocaleTimeString());
//]]>
</script>
29. isNaN
<script type="text/javascript">
//<![CDATA[
var $str='this is string';
var $num=12.3;
//alert(isNaN($str));
alert(isNaN($num));
//]]>
</script>
28. new 語(yǔ)法
new Boolean(false)
new Number(0)
new String("")
new Array()
new Object()
new Date();
new Error();
27. RegExp
27.1 普通操作 1
<script type="text/javascript">
//<![CDATA[
var $str='this is a test'
with(document){
write('test str is: '+$str+'<br/>');
write('$str.search(/is a/i): '+$str.search(/is a/i)+'<p/>');
write('$str.replace(/ {1,1}/ig,"--"): '+$str.replace(/ {1,1}/ig,"--")+'<p/>');
write('$str.match(/t[\S]{1,3}/ig): '+$str.match(/t[\S]{1,3}/ig)+'<p/>');
var $temp=$str.match(/(t[\S]{1,3})/ig)
for ($i=0; $i<$temp.length; $i++){
write($temp[$i]+'<br/>');
}
}
//]]>
</script>
27.2 test 語(yǔ)句
<script type="text/javascript">
//<![CDATA[
var $pattern=/this/i;
alert($pattern.test('this is a test'));
//]]>
</script>
27.3 exec 語(yǔ)句
<script type="text/javascript">
//<![CDATA[
var $pattern=/this/ig;
var $str='this is a test, this is repeat';
var $result;
while(($result=$pattern.exec($str))!=null){
alert($result[0]+'>>> index of str: '+$result.index+' $pattern lastIndex: '+$pattern.lastIndex);
}
//]]>
</script>
26. Array()
26.0 簡(jiǎn)單創(chuàng)建數(shù)組, 并賦值
<script type="text/javascript">
//<![CDATA[
var ar=new Array();
for(var i=0; i<10; i++){
ar[i]='array '+i
document.write(ar[i]+'<br/>');
}
//]]>
</script>
26.0.1 簡(jiǎn)單創(chuàng)建數(shù)組, 并賦值 2
<script type="text/javascript">
//<![CDATA[
var ar=['v1', 'v2', 'v3', 'v4', 'v5']
for(var i=0; i<ar.length; i++){
document.write(ar[i]+'<br/>');
}
//]]>
</script>
26.0.2 簡(jiǎn)單創(chuàng)建數(shù)組
<script type="text/javascript">
//<![CDATA[
var ar=new Array(10);
document.write(ar.length);
//]]>
</script>
26.0.3 創(chuàng)建數(shù)組中的數(shù)組
<script type="text/javascript">
//<![CDATA[
var ar=new Array('v1', 'v2', 'v3', ['v41', 'v42']);
for(var i=0; i<ar.length; i++){
document.write(ar[i].toString()+'<br/>');
}
//]]>
</script>
26.0.4 創(chuàng)建數(shù)組中的對(duì)象
<script type="text/javascript">
//<![CDATA[
var ar=new Array('v1', 'v2', 'v3', {x:'v41', y:'v42'});
for(var i=0; i<ar.length; i++){
if(typeof(ar[i])=='string')
document.write(ar[i]+'<br/>');
else if(typeof(ar[i])=='object'){
document.write('object<br/>');
for(var j in ar[i]){
document.write('obj: '+j+' obj val '+ar[i][j]+'<br/>');
}
}
}
//]]>
</script>
26.1 [array].push(), [array].pop()
<script type="text/javascript">
//<![CDATA[
var $array=new Array('a', 'b', 'c', 'd', 'e')
with(document){
write('source $array.join: '+$array.join()+'<br/>');
write ($array.length+'<br/>');
$array.push(1,1,1,1,1,1,1,1,1,1);
write ('$array.push(1,1,1,1,1,1,1,1,1,1), $array.length: '+$array.length+'<br/>');
write('join $array: '+$array.join()+'<p/>');
write ($array.length+'<br/>');
$array.push(1, 2, 3, 4, 5);
write ('$array.push(1, 2, 3, 4, 5), $array.length: '+$array.length+'<br/>');
write('join $array: '+$array.join()+'<p/>');
write('$array.pop(): '+$array.pop()+'<br/>');
write('$array.length & $array.join(): '+$array.length+' '+$array.join()+'<p/>');
write('$array.pop(10): '+$array.pop(10)+'<br/>');
write('$array.length & $array.join(): '+$array.length+' '+$array.join()+'<br/>');
}
//]]>
</script>
26.2 數(shù)組排序
<script type="text/javascript">
//<![CDATA[
var a=new Array();
for (var i=0, j=1; i<10;a[i]=j, i++, j++);
document.write('<h2>未排序前:</h2>');
document.write(a.join());
document.write('<h2>無(wú)條件排序:</h2>');
document.write(a.sort().join());
temp=a.sort(function(a, b){return a-b});
document.write('<h2>a-b 排序:</h2>');
document.write(temp.join());
temp=a.sort(function(a, b){return b-a});
document.write('<h2>b-a 排序:</h2>');
document.write(temp.join());
//]]>
</script>
26.3 創(chuàng)建數(shù)組指定維數(shù), 從 1 開(kāi)始.
<script type="text/javascript">
//<![CDATA[
var a=new Array(3);
document.write((a.length+'').bold()+'<br/>');
for(var i=0; i<a.length; i++){
document.write(i+'<br/>');
}
//]]>
</script>
25. toString
25.1 使用 toString 列出數(shù)組中的元素
<script type="text/javascript">
//<![CDATA[
var $array=new Array('a', 'a1', 'a2');
alert($array.toString());
//]]>
</script>
24. object
24.1 創(chuàng)建簡(jiǎn)單對(duì)象
<script type="text/javascript">
//<![CDATA[
var $obj=new Object();
$obj={$title:"object example", $date:Date()}
alert($obj.$date);
//]]>
</script>
24.1.1 創(chuàng)建簡(jiǎn)單對(duì)象 一
<script type="text/javascript">
//<![CDATA[
var cnt=new Object();
cnt.title='title this';
cnt.content='content this'
cnt.date='the publishing date of '+Date();
document.write('title: '+cnt.title+'<br/>cnt.content: '+cnt.content+'<br/>cnt.date: '+cnt.date);
//]]>
</script>
24.1.2 創(chuàng)建簡(jiǎn)單對(duì)象 二
<script type="text/javascript">
//<![CDATA[
var cnt={
title:'title this',
content:'content this',
date:'the publishing date of '+Date()
}
document.write('title: '+cnt.title+'<br/>cnt.content: '+cnt.content+'<br/>cnt.date: '+cnt.date);
//]]>
</script>
24.2 創(chuàng)建嵌套對(duì)象
<script type="text/javascript">
//<![CDATA[
var cnt={
title:{
headertitle:'header title',
subtitle:'subtitle this'
},
content:'content this',
date:'the publishing date of '+new Date().toLocaleString()
}
document.write('title: '+cnt.title.headertitle.bold().fontcolor('red')+
'<br/>cnt.title.subtitle: '+cnt.title.subtitle.fontcolor('blue')+
'<br/>cnt.content: '+cnt.content.fontcolor('goldenrod')+
'<br/>cnt.date: '+cnt.date);
//]]>
</script>
24.2.1 創(chuàng)建嵌套對(duì)象 1
<script type="text/javascript">
//<![CDATA[
var o=new Object();
o.title=' this title ';
o.content=' this content';
o.lve=new Object();
o.lve.title=' this o.lve title';
o.lve.content=' this o.lve content';
document.write('o.title: '+o.title.bold()+'<br/>');
document.write('o.content: '+o.content.bold()+'<br/>');
document.write('o.lve.title: '+o.lve.title.bold()+'<br/>');
document.write('o.lve.content: '+o.lve.content.bold()+'<br/>');
//]]>
</script>
24.3 刪除對(duì)象中的屬性
<script type="text/javascript">
//<![CDATA[
var $obj=new Object();
$obj={$title:"object example", $date:Date()}
//alert($obj.$date);
var $name="";
for(name in $obj)$name+=name+'\n';
alert($name);
delete $obj.$date
var $name="";
for(name in $obj)$name+=name+'\n';
alert($name);
//]]>
</script>
24.4 遍歷對(duì)象中的屬性名
<script type="text/javascript">
//<![CDATA[
var $obj=new Object();
$obj={$title:"object example", $date:Date()}
//alert($obj.$date);
var $name="";
for(name in $obj)$name+=name+'\n';
alert($name);
//]]>
</script>
24.4.1 遍歷對(duì)象中的屬性名 1
<script type="text/javascript">
//<![CDATA[
var o=new Object();
o.title=' this title ';
o.content=' this content';
o.lve=new Object();
o.lve.title=' this o.lve title';
o.lve.content=' this o.lve content';
for (var i in o){
if(typeof o[i]!=='object'){
document.write('object o, element: '+i.fontcolor('red')+' value: '+o[i].bold()+'<br/>');
} else {
document.write('object '+i+' element<br/>');
for(var j in o[i]){
document.write('subobject element :'+j.fontcolor('red')+
' subobject value: '+o[i][j].bold()+'<br/>');
}
}
}
//]]>
</script>
24.5 obj.propertyIsEnumerable('ele')
<script type="text/javascript">
//<![CDATA[
var d=new Date();
d.x='test';
var s=new String();
var o=new Object();
var f=new Function('thest')
document.write(d.propertyIsEnumerable('x'));
document.write(d.propertyIsEnumerable('y'));
//]]>
</script>
24.6 obj.hasOwnProperty('ele')
<script type="text/javascript">
//<![CDATA[
var d=new Date();
d.x='test';
var s=new String();
var o=new Object();
var f=new Function('thest')
document.write(d.hasOwnProperty('x'));
document.write(d.hasOwnProperty('y'));
//]]>
</script>
23. call, apply
23.1 apply
23.1.1 找出數(shù)組中最大的數(shù)
<script type="text/javascript">
//<![CDATA[
$array=new Array(2, 9, 12, 33, 2, 4444, 22)
var $temp=Math.max.apply(null, $array)
alert($temp)
//]]
</script>
22. break, continue
22.1 continue
<script type="text/javascript">
//<![CDATA[
for (var $i=0; $i<10; $i++){
if($i==5){continue;}
document.write ($i+'<br/>')
}
//]]>
</script>
22.2 break
22.2.1 break 標(biāo)簽
<script type="text/javascript">
//<![CDATA[
//document.write('<xmp>');
outerloop:
for (var i=0; i<10; i++){
document.writeln(('outerloop:'+i).bold()+'<br/>')
innerloop:
for(var j=0; j<10; j++){;
if(i==5)break outerloop;
if(j==9)break innerloop;
document.writeln(('innerloop: '+j).fontcolor('blue')+'<br/>');
}
}
//document.write('</xmp>');
//]]>
</script>
21. with
21.1 簡(jiǎn)單 with
<script type="text/javascript">
//<![CDATA[
with(document){
write('ok');
}
//]]>
</script>
21.1 簡(jiǎn)單with (另一寫(xiě)法)
var $dw=document
$dw.write('ok this a test');
20. try, catch, finally
20.1 簡(jiǎn)單 try, catch
try{
5*kkk
}
catch(e){
alert(e)
}
20.1.1 簡(jiǎn)單 try, catch 1
<script type="text/javascript">
//<![CDATA[
document.write('<h2>window object:</h2>');
for(var i in window){
try{
document.write(i.bold()+' '+(window[i]+'').fontcolor('blue')+'<br/>');
} catch (e) {
document.write(i.fontcolor('red').bold()+': ');
document.write(e.description.fontcolor('red')+'<br/>');
}
}
//]]>
</script>
19. for in
19.1 簡(jiǎn)單 for in
<script type="text/javascript">
//<![CDATA[
/* document.write('<h2>top object:</h2>');
for(var i in top){
try{
document.write(i.bold()+' '+(top[i]+'').fontcolor('blue')+'<br/>');
} catch (e) {
document.write(i.fontcolor('red').bold()+': ');
document.write(e.description.fontcolor('red')+'<br/>');
}
}
document.write('<h2>parent object:</h2>');
for(var i in parent){
try{
document.write(i.bold()+' '+(parent[i]+'').fontcolor('blue')+'<br/>');
} catch (e) {
document.write(i.fontcolor('red').bold()+': ');
document.write(e.description.fontcolor('red')+'<br/>');
}
}
document.write('<h2>screen object:</h2>');
for(var i in screen){
try{
document.write(i.bold()+' '+(screen[i]+'').fontcolor('blue')+'<br/>');
} catch (e) {
document.write(i.fontcolor('red').bold()+': ');
document.write(e.description.fontcolor('red')+'<br/>');
}
}
*/
try{
document.write('<h2>clipboardData object:</h2>');
for(var i in clipboardData){
try{
document.write(i.bold()+' '+(clipboardData[i]+'').fontcolor('blue')+'<br/>');
} catch (e) {
document.write(i.fontcolor('red').bold()+': ');
document.write(e.description.fontcolor('red')+'<br/>');
}
}
} catch(ex) {
document.write((ex+'').fontcolor('red'));
}
document.write('<h2>window object:</h2>');
for(var i in window){
try{
document.write(i.bold()+' '+(window[i]+'').fontcolor('blue')+'<br/>');
} catch (e) {
document.write(i.fontcolor('red').bold()+': ');
document.write(e.description.fontcolor('red')+'<br/>');
}
}
/*
document.write('<h2>Option object:</h2>');
for(var i in Option){
try{
document.write(i.bold()+' '+(Option[i]+'').fontcolor('blue')+'<br/>');
} catch (e) {
document.write(i.fontcolor('red').bold()+': ');
document.write(e.description.fontcolor('red')+'<br/>');
}
}
*/
document.write('<h2>frames object:</h2>');
for(var i in frames){
try{
document.write(i.bold()+' '+(frames[i]+'').fontcolor('blue')+'<br/>');
} catch (e) {
document.write(i.fontcolor('red').bold()+': ');
document.write(e.description.fontcolor('red')+'<br/>');
}
}
/*
document.write('<h2>self object:</h2>');
for(var i in self){
try{
document.write(i.bold()+' '+(self[i]+'').fontcolor('blue')+'<br/>');
} catch (e) {
document.write(i.fontcolor('red').bold()+': ');
document.write(e.description.fontcolor('red')+'<br/>');
}
}
*/
document.write('<h2>document object:</h2>');
for(var i in document){
document.write(i.bold()+' '+(document[i]+'').fontcolor('blue')+'<br/>');
}
document.write('<h2>history object:</h2>');
for(var i in history){
try{
document.write(i.bold()+' '+(history[i]+'').fontcolor('blue')+'<br/>');
} catch (e) {
document.write(i.fontcolor('red').bold()+': ');
document.write(e.description.fontcolor('red')+'<br/>');
}
}
/*
document.write('<h2>Image object:</h2>');
for(var i in Image){
try{
document.write(i.bold()+' '+(Image[i]+'').fontcolor('blue')+'<br/>');
} catch (e) {
document.write(i.fontcolor('red').bold()+': ');
document.write(e.description.fontcolor('red')+'<br/>');
}
}
*/
document.write('<h2>navigator object:</h2>');
for(var i in navigator){
try{
document.write(i.bold()+' '+(navigator[i]+'').fontcolor('blue')+'<br/>');
} catch (e) {
document.write(i.fontcolor('red').bold()+': ');
document.write(e.description.fontcolor('red')+'<br/>');
}
}
document.write('<h2>location object:</h2>');
for(var i in location){
document.write(i.bold()+' '+(location[i]+'').fontcolor('blue')+'<br/>');
}
//]]>
</script>
19.1.1 簡(jiǎn)單 for in 1
for (var $i in window){
document.write($i+'<br/>');
}
19.2 for in 賦值 [數(shù)組]
var $array=new Array();
var i=0;
for ($array[i++] in window){
//document.write($i+'<br/>');
}
alert($array[0]);
19.2.1 for in 賦值 [數(shù)組] 1
<script type="text/javascript">
//<![CDATA[
var o={a:'aaa', b:'bbb', c:'ccc'};
var a=new Array();
var i=0;
for(a[i++] in o)document.write(a[i-1]);
//for(i in a)document.write(a[i]);
//]]>
</script>
18. for
18.1 簡(jiǎn)單 for
for (var $i=0; $i<10; $i++) {
document.write($i)
}
18.2 簡(jiǎn)單 for 1
for (var $i=0, $j=10; $i<10; $i++, $j--) {
document.write(($i*$j)+'<br/>')
}
18.3 循環(huán)列出從 a - z 的字母
<script type="text/javascript">
//<![CDATA[
for(var $i='a'.charCodeAt(); $i<='z'.charCodeAt(); $i++){
document.write(String.fromCharCode($i)+'<br/>')
}
//]]>
</script>
18.3 n階乘
<script type="text/javascript">
//<![CDATA[
var $fN=10
for (var $i=1, $j=1; $i<=$fN; $i++, $j*=$i){
if($i==$fN){document.write($j);}
}
//]]>
</script>
18.4 Fibonacci Numbers
<script type="text/javascript">
//<![CDATA[
for(var $i=0, $j=1, $k=0, $fbcc=0; $i<50; $i++){
document.write($i+'='+$fbcc+'<br/>');
$fbcc=$j+$k;
$j=$k;
$k=$fbcc;
}
//]]>
</script>
17. do while
17.1 簡(jiǎn)單 do while
var $count=0
do{
document.write($count)
} while(++$count<10)
17.1.2 簡(jiǎn)單 do while
var $count=1
do{
document.write($count)
} while($count++<10)
16. while
16. 簡(jiǎn)單 while
var $count=0
while($count<10){ document.write($count);$count++;}
15 if 判斷
15.1 簡(jiǎn)單 if 判斷
function ubbTag(fId, str){
document.getElementById(fId).content.focus();
var strEnd=str.replace(/\[/ig,'[/')
if (strEnd.indexOf('=')>-1){ strEnd=strEnd.replace(/(.*?)\=.*?\]/,'$1]') }
if((document.selection)&&(document.selection.type== "Text")){
var oStr=document.selection.createRange();
oStr.text=str+oStr.text+strEnd
} else {
document.getElementById(fId).content.value+=str+strEnd
}
}
15.1.1 簡(jiǎn)單 if 判斷 2
<script type="text/javascript">
//<![CDATA[
var i=0, j=1;
i>j?j+=i:i+=j;
document.write(i+' '+j);
//]]>
</script>
15.1.2 簡(jiǎn)單 if 判斷 3
<script type="text/javascript">
//<![CDATA[
if(!cdti||cdti=='')var cdti='test this';
document.write(cdti);
//]]>
</script>
15.2 if 判斷的 三個(gè) 寫(xiě)法
<script type="text/javascript">
//<![CDATA[
var a=b=5, c=6
if(a==b)document.write('a equal b <br/>');
(a==b)&&document.write('a equal b <br/>');
a==b?document.write('a equal b <br/>'):'';
//]]>
</script>
15.3 判斷執(zhí)行文件使用網(wǎng)絡(luò)還是使用本地協(xié)議
<script type="text/javascript">
//<![CDATA[
if(location.protocol=='file:'){
alert('local')
} else alert('internet');
//]]>
</script>
15.4 if...else 寫(xiě)法
<script type="text/javascript">
//<![CDATA[
//var i=0
var i=1
if(i==0)document.write('i=0');
else document.write('i!=0');
//]]>
</script>
14. switch
14.1 簡(jiǎn)單 switch
/* switch(strEnd){
case '\[\/html]' :strEnd=strEnd.replace(/\\[\/,'HTML 和 JS 代碼支持[');break;
case '\[\/code]' :strEnd=strEnd.replace(/\\[\/,'代碼[');break;
case '\[\/quote]' :strEnd=strEnd.replace(/\\[\/,'引用[');break;
case '\[\/cite]' :strEnd=strEnd.replace(/\\[\/,'引用[');break;
case '\[\/linenum]' :strEnd=strEnd.replace(/\\[\/,'顯示行號(hào)[');break;
case '\[\/b]' :strEnd=strEnd.replace(/\\[\/,'粗體[');break;
case '\[\/i]' :strEnd=strEnd.replace(/\\[\/,'敘體[');break;
case '\[\/u]' :strEnd=strEnd.replace(/\\[\/,'下劃線(xiàn)[');break;
case '\[\/flash]' :strEnd=strEnd.replace(/\\[\/,'Flash 動(dòng)畫(huà)[');break;
case '\[\/sound]' :strEnd=strEnd.replace(/\\[\/,'背景聲音[');break;
case '\[\/mms]' :strEnd=strEnd.replace(/\\[\/,'WM格式流數(shù)據(jù)[');break;
case '\[\/rtsp]' :strEnd=strEnd.replace(/\\[\/,'Real格式流數(shù)據(jù)[');break;
case '\[\/ra]' :strEnd=strEnd.replace(/\\[\/,'在線(xiàn)Real Player播放音頻文件[');break;
case '\[\/real]' :strEnd=strEnd.replace(/\\[\/,'Real Player 播放視頻文件[');break;
case '\[\/wm]' :strEnd=strEnd.replace(/\\[\/,'在線(xiàn)Windows Media Player播放視頻文件[');break;
case '\[\/wma]' :strEnd=strEnd.replace(/\\[\/,'在線(xiàn)Windows Media Player播放音頻文件[');break;
case '\[\/iframe]' :strEnd=strEnd.replace(/\\[\/,'插入網(wǎng)頁(yè)[');break;
} */
13. 時(shí)間操作
13.1 以毫秒為單位的倒計(jì)時(shí)跳轉(zhuǎn), 來(lái)源 CSDN
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
//<![CDATA[
var go=20000;
var timer=null;
var endTime = new Date().getTime() + go ;
function interval()
{
var n=(endTime-new Date().getTime())/1000;
if(n<0) return;
document.getElementById("jumpTo").innerHTML = n.toFixed(3);
setTimeout(interval, 10);
}
window.onload=function(){
timer=setTimeout("window.location.href='/'", go);
interval();
}
//]]>
</script>
<span id="jumpTo">20.000</span> 秒后 將自動(dòng)</span>跳轉(zhuǎn)到
12. 隨機(jī)數(shù)
12.1 生成 GUID
<!--start 12.1-->
<html>
<!-- DW6 -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<script>
function fGuid()
{
var g ="";
for(var i = 0; i < 32; i++)
g += Math.floor(Math.random() * 0xF).toString(0xF) + (i == 8 || i == 12 || i == 16 || i == 20 ? "-" : "");
alert(g.toUpperCase());
}
</script>
</head>
<body onLoad="fGuid();">
</body>
</html>
<!--end 12.1-->
12.1.1 生成 GUID 2
<!--start 12.1.1 -->
<html>
<!-- DW6 -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<script>
function fGuid() {
var g ="";
for(var i = 0; i < 32; i++)
g += Math.floor(Math.random() * 0xF).toString(0xF) + (i == 8 || i == 12 || i == 16 || i == 20 ? "-" : "");
//alert(g.toUpperCase());
return g.toUpperCase();
}
</script>
</head>
<body>
<form name="form1" method="post" action="">
<input name="textfield" type="text" onMouseMove="this.value=fGuid();" size="50">
</form>
</body>
</html>
<!--end 12.1.1 -->
11.1 檢測(cè)字符串中是否出現(xiàn)某字符
<script>
function test(str) {
if(str.indexOf("|")>0) {
alert("have |")
}
}
</script>
<input type="text" value="kklskldflksd|ksdkfksjd" onMouseOver="test(this.value)" />
11. 字符串
10.2 鼠標(biāo)移過(guò)選擇表單項(xiàng)
onMouseOver="focus();select();"
10.1 單擊鼠標(biāo)右擊關(guān)閉窗口 (我用左手)
<html onmousedown='window.close();'>
10. 接收鼠標(biāo)事件
9. 正則表達(dá)式
function rbr() {
re=/\<br\/\>*/ig
document.all.textarea.value=document.all.textarea.value.replace(re,"")
}
8. 顯示頁(yè)面所有元素
<script language="JavaScript" type="text/javascript">
//<![CDATA[
for(var i in document) {
document.write(i +"="+ document[i]+"<br/>")
}
//]]>
</script>
7. 文本框回車(chē)鏈接
<script>
<!--
function ckKeyPress(jumpto){
if(window.event.keyCode==13) {
window.location.href="?"+jumpto
}
}
//-->shawl.qiu script
</script>
轉(zhuǎn)到:<input type='text' onmousemove='this.focus();this.select();' onkeypress="ckKeyPress(this.value);" />
6. IE 全屏顯示
<script language="JavaScript">
<!--
self.moveTo(0,0)
self.resizeTo(screen.availWidth,screen.availHeight)
//-->
</script>
5. 雙擊拷貝文本
<script LANGUAGE="JAVASCRIPT">
function ClipBoard(tdObj) { //IE Only
var holdtext = document.all['holdtext'];
holdtext.innerText = tdObj.innerText;
Copied = holdtext.createTextRange();
Copied.execCommand("Copy");
alert("text copied");
}
</script>
<form NAME="form1" METHOD="post" ACTION="">
<textarea id="holdtext" style="display:none" ROWS="10"></textarea>
</form>
4. 控制圖片大小
<img src="images/teach/opera/01.jpg" onload="javascript:if(this.width>500)this.width=500;" >
//如果圖片寬度大于 500px, 則 更改寬度為 500px
3.1 Javascript 結(jié)合 Asp 使用數(shù)組
<% '連接數(shù)據(jù)庫(kù)
set rs=server.CreateObject("adodb.recordset") '創(chuàng)建 rs 數(shù)據(jù)查詢(xún)
rs.open "Select a.*, b.* FROM ctglossarysubcat AS a INNER JOIN ctglossarysupercat AS b ON a.gcid = b.gcid order by a.gcid",MM_conn_string,1
%>
<script LANGUAGE="JAVASCRIPT">
var onecount; //定義子類(lèi)計(jì)數(shù)
onecount=0; //設(shè)置子類(lèi)計(jì)數(shù)默認(rèn)值為0
subcat = new Array(); //定義顯示子類(lèi)數(shù)組
<% count = 0
do while not rs.eof %>
subcat[<%=count%>] = new Array("<%=rs("gscat")%>","<%=rs("a.gcid")%>","<%=rs("gscid")%>");
<% count = count + 1
rs.movenext
loop
%>
onecount=<%=count%>; //子類(lèi)條目總數(shù)
</script>
<%
rs.close '關(guān)閉 rs 連接
set rs=nothing
%>
3. 數(shù)組/Array
2.2 實(shí)時(shí)顯示更改的圖片鏈接
<input type="text" name="" value="<%response.write siteicon %>" onkeyup="javascript:document.all.siteicon.src=(this.value);" /> <img src="<%response.write siteicon %>" alt="<%response.write sitename %>" id="siteicon" />
2.1 按任何鍵關(guān)閉窗口
<body onKeyPress="self.close()">
2. 接收鍵盤(pán)事件
1.6 鼠標(biāo)經(jīng)過(guò)自動(dòng)提交表單
onMouseOut="submit()"
1.5.1 鼠標(biāo)經(jīng)過(guò)時(shí)選中,并隱藏原框的文字, 移開(kāi)再顯示文字 ——文本框
<input NAME="findtext" TYPE="text" ID="findtext" value="查找" onMouseOver="this.focus();this.value=''" onMouseOut="this.value='查找';this.select()">
<!-- shawl.qiu script -->
1.5 鼠標(biāo)經(jīng)過(guò)時(shí)選中 ——復(fù)選框 Focus()
<input type="checkbox" onMouseOver="checked='true'" />
<!-- shawl.qiu script -->
1.4 Prompt
function prompter()
{
urlLink=window.prompt("請(qǐng)輸入鏈接","
http://")
text = window.prompt("鏈接名")
if(text!="")
document.formT.content.value+=""+text+""
}
1.3 最原始也最實(shí)用的 UBB 代碼輸入方法——SCRIPT & FORM
<form name="formT" id="formT" method="post" action="">
<input type="button" value="url" onclick="this.form.content.value+=''"/>
<input type="button" value="code" onclick="this.form.content.value+='
CODE:'" />
<input type="button" value="quote" onclick="this.form.content.value+='
QUOTE:
'"/>
<br />
<textarea name="content" cols="60" rows="10"></textarea>
<br />
<input type="submit" name="Submit" value="Submit" />
<input type="reset" name="Reset" value="Reset" />
</form>
<!-- shawl.qiu script -->
1.2 確認(rèn)按鈕
<script LANGUAGE="JavaScript">
<!--//確認(rèn)框, 注意表單名; 按鈕屬性, 按鈕名字不能為 submit
function confirmer()
{
if (confirm("現(xiàn)在提交?")) {
document.formT.submit()
}
else {
document.formT.reset()
}
}gggg
//Script By Shawl.qiu
//-->
</script>
<form name="formT" method="post" action="t1.asp">
<input type="text" name="textfield" value="確認(rèn)后提交">
<input type="button" name="confbuton" value="提交" onclick="confirmer();">
</form>
1.1 前進(jìn)后退按鈕
<input TYPE="button" VALUE="后退" ONCLICK="history.back(-1)">
<input TYPE="button" VALUE="前進(jìn)" ONCLICK="history.back(+1)">
1. 按鈕
0. 語(yǔ)法
0.1 Switch
function kP() {
switch(event.keyCode) {
case 27: //按 ESC 鍵關(guān)閉窗口.
window.close()
break;
//case 120: //F9 轉(zhuǎn)到主頁(yè)
//window.location.href="/"
//break;
default:
break;
}
}
-1. 運(yùn)算符
-1.1 -- 與 ++
<script type="text/javascript">
//<![CDATA[
var x;
x=0;
document.write('x=0, x++: '+(x++)); // 執(zhí)行 x 后, x 再加 1
x=0;
document.write('<br/>x=0, ++x: '+(++x)); // 執(zhí)行 x 前, x 先加 1
x=2;
document.write('<br/>x=2, x--: '+(x--)); // 執(zhí)行 x 后, x 再減 1
x=2;
document.write('<br/>x=2, --x: '+(--x)); // 執(zhí)行 x 前, x 先減 1
//]]>
</script>
-1.1.1
<script type="text/javascript">
//<![CDATA[
var i=1;
j=++i;
document.write(i); //2
document.write('<br/>');
document.write(j); //2
document.write('<br/>');
var k=1
l=k++
document.write(k); //2
document.write('<br/>');
document.write(l); //1
//]]>
</script>
-1.2 類(lèi)型轉(zhuǎn)換
<script type="text/javascript">
//<![CDATA[
document.write('100'+100); //'100100' 字符串與數(shù)字相加
document.write('<br/>');
document.write('100'-0); //100 轉(zhuǎn)字符串為數(shù)值
document.write('<br/>');
document.write(100+''); //'100' 數(shù)值轉(zhuǎn)字符串
document.write('<br/>');
document.write(!!100); //true 轉(zhuǎn)布爾值
document.write('<br/>');
document.write(!100); //false 轉(zhuǎn)布爾值
document.write('<br/>');
//]]>
</script>
-1.3 0/0=?
<script type="text/javascript">
//<![CDATA[
document.write(0/0); //NaN
//]]>
</script>
-1.4 == 與 ===
-1.4.1 NaN
<script type="text/javascript">
//<![CDATA[
document.write(NaN==NaN); //false
document.write(NaN===NaN); //false
//]]>
</script>
-1.4.2 true 等價(jià) 1, false 等價(jià) 0.
<script type="text/javascript">
//<![CDATA[
document.write(1==true); //true
document.write('<br/>');
document.write(0==false); //true
document.write('<br/>');
//]]>
</script>
-1.5 in 操作符
<script type="text/javascript">
//<![CDATA[
var o={e:'ok', f:'ok'}
document.write('e' in o); // true
document.write('<br/>');
document.write('f' in o); // true
document.write('<br/>');
document.write('j' in o); // false
document.write('<br/>');
document.write('toString' in o); // false
document.write('<br/>');
//]]>
</script>
-2. var 定義變量
-2.1 普通定義變量
<script type="text/javascript">
//<![CDATA[
var i
document.write(i+'<br/>');
var j=1, k=2
document.write(j+k+'<br/>');
for(var l=0; l<10; l++)document.write(l+' ');;
//]]>
</script>
-2.1.1 普通定義變量 1
<script type="text/javascript">
//<![CDATA[
var o={a:'aaa', b:'bbb', c:'ccc'}
for(var i in o){
document.write('object element name: '+i.bold()+' object value: '+o[i].fontcolor('blue')+'<br/>');
}
//]]>
</script>
-2.1.2 普通定義變量 2
<script type="text/javascript">
//<![CDATA[
var i=j=k=l='ok';
document.write(i.bold()+'<br/>');
document.write(j.bold()+'<br/>');
document.write(k.bold()+'<br/>');
document.write(l.bold()+'<br/>');
//]]>
</script>
-2.2 全局變量與局部變量
<script type="text/javascript">
//<![CDATA[
var i='global i';//全局
function t(){
var i='local i'; //局部
document.write(i+'<br/>');
j='global j' //全局
document.write(j+'<br/>');
}
document.write(i+'<br/>');
t();
document.write(i+'<br/>');
document.write(j+'<br/>');
var k='global k'
document.write(k+'<br/>');
function t1(){
k='change global k'
document.write(k+'<br/>');
}
t1();
document.write(k+'<br/>');
//]]>
</script>
-2.3 在函數(shù)中使用 var 定義一個(gè)變量, 該變量將影響整個(gè)函數(shù), 不分先后.
var scope = "global";
function f( ) {
alert(scope); // Displays "undefined", not "global"
var scope = "local"; // Variable initialized here, but defined everywhere
alert(scope); // Displays "local"
}
f( );
-2.4 同時(shí)初始化多個(gè)變量并賦相同值
<script type="text/javascript">
//<![CDATA[
var i=j=k=l=0;
document.write(i+' '+j+' '+k+' '+l+' ');
//]]>
</script>
-3. 優(yōu)先級(jí)
-3.1 函數(shù)比其他代碼優(yōu)先執(zhí)行
<script type="text/javascript">
//<![CDATA[
document.write((t(10)+'').bold()+'<br/>');
t=10;
document.write((t+'').bold()+'<br/>');
function t(n){
return n*n;
}
//]]>
</script>
---/---------------------------------------------------------
常用參數(shù)
3. document
2. location
1. this
---------------------------------
3.3 寫(xiě)出字符串
document.write("<input type='button' value='url' onclick='addcontent('','');'/>");
3.2 document.from
指定 表單域
3.1 document.all.id
查找指定 HTML 頁(yè)面 ID 或 名字
3. document
2.2 轉(zhuǎn)到特定網(wǎng)頁(yè)
onClick="location.href='
http://127.0.0.1/'"
2.1 單獨(dú) location
取頁(yè)面地址
2. location
1.4 this.height
取高度屬性
1.3 this.width
取寬度屬性
1.2 this.href
取鏈接地址
1.1 this.src
取圖片地址
1. this
---/---------------------------------------------------------
問(wèn)題集:
3. return 返回多個(gè)值 2006-10-14 14:13:18
2. 理解 setInternal 用法
1. 理解 void 用法
---/---------------------------------------------------------
相關(guān)摘要:
24. Keep in mind that the function statement is available in all versions of JavaScript, the Function( ) constructor is available only in JavaScript 1.1 and later, and function literals are available only in JavaScript 1.2 and later. Recall that we said the three functions defined earlier are "more or less" equivalent -- there are some differences between these three techniques for function definition, which we'll consider in Section 11.5.
//JavaScript: The Definitive Guide, 4th Edition -- 7.1.3 Function Literals
2006-10-19 14:35:56
23. The Function( ) constructor expects any number of string arguments. The last argument is the body of the function -- it can contain arbitrary JavaScript statements, separated from each other by semicolons. All other arguments to the constructor are strings that specify the names of the parameters to the function being defined. If you are defining a function that takes no arguments, you simply pass a single string -- the function body -- to the constructor.
//JavaScript: The Definitive Guide, 4th Edition -- 7.1.2 The Function( ) Constructor
2006-10-19 14:16:18
22. Note that ECMAScript v3 does not allow function definitions to appear anywhere; they are still restricted to top-level global code and top-level function code. This means that function definitions may not appear within loops or conditionals, for example.[1] These restrictions on function definitions apply only to function declarations with the function statement. As we'll discuss later in this chapter, function literals (another feature introduced in JavaScript 1.2 and standardized by ECMAScript v3) may appear within any JavaScript e-xpression, which means that they can appear within if and other statements.
//JavaScript: The Definitive Guide, 4th Edition -- 7.1 Defining and Invoking Functions
2006-10-19 14:10:13
21. try and finally can be used together without a catch clause. In this case, the finally block is simply cleanup code that is guaranteed to be executed, regardless of any break, continue, or return statements within the try clause. For example, the following code uses a try/finally statement to ensure that a loop counter variable is incremented at the end of each iteration, even when an iteration terminates abruptly because of a continue statement:
//JavaScript: The Definitive Guide, 4th Edition -- 6.17 try/catch/finally
2006-10-18 19:18:08
20. The continue statement, in both its labeled and unlabeled forms, can be used only within the body of a while, do/while, for, or for/in loop. Using it anywhere else causes a syntax error.
//JavaScript: The Definitive Guide, 4th Edition -- 6.12 continue
2006-10-18 16:03:46
19. The following rules are used to determine whether two values are identical according to the === operator:
If the two values have different types, they are not identical.
If both values are numbers and have the same value, they are identical, unless either or both values are NaN, in which case they are not identical. The NaN value is never identical to any other value, including itself! To check whether a value is NaN, use the global isNaN( ) function.
If both values are strings and contain exactly the same characters in the same positions, they are identical. If the strings differ in length or content, they are not identical. Note that in some cases, the Unicode standard allows more than one way to encode the same string. For efficiency, however, JavaScript string comparison compares strictly on a character-by-character basis, and it assumes that all strings have been converted to a "normalized form" before they are compared. See the "String.localeCompare( )" reference page in the core reference section of this book for another way to compare strings.
If both values are the boolean value true or both are the boolean value false, they are identical.
If both values refer to the same object, array, or function, they are identical. If they refer to different objects (or arrays or functions) they are not identical, even if both objects have identical properties or both arrays have identical elements.
If both values are null or both values are undefined, they are identical.
The following rules are used to determine whether two values are equal according to the == operator:
If the two values have the same type, test them for identity. If the values are identical, they are equal; if they are not identical, they are not equal.
If the two values do not have the same type, they may still be equal. Use the following rules and type conversions to check for equality:
If one value is null and the other is undefined, they are equal.
If one value is a number and the other is a string, convert the string to a number and try the comparison again, using the converted value.
If either value is true, convert it to 1 and try the comparison again. If either value is false, convert it to 0 and try the comparison again.
If one value is an object and the other is a number or string, convert the object to a primitive and try the comparison again. An object is converted to a primitive value by either its toString( ) method or its valueOf( ) method. The built-in classes of core JavaScript attempt valueOf( ) conversion before toString( ) conversion, except for the Date class, which performs toString( ) conversion. Objects that are not part of core JavaScript may convert themselves to primitive values in an implementation-defined way.
Any other combinations of values are not equal.
As an example of testing for equality, consider the comparison:
"1" == true
This e-xpression evaluates to true, indicating that these very different-looking values are in fact equal. The boolean value true is first converted to the number 1, and the comparison is done again. Next, the string "1" is converted to the number 1. Since both numbers are now the same, the comparison returns true.
When the equality operator in JavaScript 1.1 attempted to convert a string to a number and failed, it displayed an error message noting that the string could not be converted, instead of converting the string to NaN and returning false as the result of the comparison. This bug has been fixed in JavaScript 1.2.
//JavaScript: The Definitive Guide, 4th Edition -- 5.4 Equality Operators
2006-10-16 21:56:30
18. In top-level code (i.e., JavaScript code that is not part of a function), you can use the JavaScript keyword this to refer to the global object. Within functions, this has a different use, which is described in Chapter 7.
//JavaScript: The Definitive Guide, 4th Edition -- 4.6 Variables as Properties
2006-10-16 16:08:34
17. Garbage collection is automatic and is invisible to the programmer. You can create all the garbage objects you want, and the system will clean up after you! You need to know only enough about garbage collection to trust that it works; you don't have to wonder about where all the old objects go. For those who aren't satisfied, however, Section 11.3, contains further details on the JavaScript garbage-collection process.
//JavaScript: The Definitive Guide, 4th Edition -- 4.5 Garbage Collection
2006-10-16 16:01:55
16. Primitive Types and Reference Types
var a = [1,2,3]; // Initialize a variable to refer to an array
var b = a; // Copy that reference into a new variable
a[0] = 99; // Modify the array using the original reference
alert(b); // Display the changed array [99,2,3] using the new reference
If this result does not seem surprising to you, you're already well familiar with the distinction between primitive and reference types. If it does seem surprising, take a closer look at the second line. Note that it is the reference to the array value, not the array itself, that is being assigned in this statement. After that second line of code, we still have only one array object; we just happen to have two references to it.
//JavaScript: The Definitive Guide, 4th Edition -- 4.4 Primitive Types and Reference Types
15. 在任何情況下,如果六個(gè)月以后您還能毫不費(fèi)力地閱讀和理解所編寫(xiě)的代碼,則說(shuō)明這些代碼寫(xiě)得不錯(cuò)。
//Windows 腳本技術(shù) -- JScript -- 什么是 JScript?
2006-10-16 14:12:55
14. The rule that all variables declared in a function are defined throughout the function can cause surprising results. The following code illustrates this:
var scope = "global";
function f( ) {
alert(scope); // Displays "undefined", not "global"
var scope = "local"; // Variable initialized here, but defined everywhere
alert(scope); // Displays "local"
}
f( );
//JavaScript: The Definitive Guide, 4th Edition -- 4.3 Variable Scope
13. Variable Scope
The scope of a variable is the region of your program in which it is defined. A global variable has global scope -- it is defined everywhere in your JavaScript code. On the other hand, variables declared within a function are defined only within the body of the function. They are local variables and have local scope. Function parameters also count as local variables and are defined only within the body of the function.
Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable. For example, the following code prints the word "local":
var scope = "global"; // Declare a global variable
function checkscope( ) {
var scope = "local"; // Declare a local variable with the same name
document.write(scope); // Use the local variable, not the global one
}
checkscope( ); // Prints "local"
//JavaScript: The Definitive Guide, 4th Edition -- 4.3 Variable Scope
2006-10-16 1:11:59
12. In general, functions do not know what variables are defined in the global scope or what they are being used for. Thus, if a function uses a global variable instead of a local one, it runs the risk of changing a value upon which some other part of the program relies. Fortunately, avoiding this problem is simple: declare all variables with var
//JavaScript: The Definitive Guide, 4th Edition -- 4.3 Variable Scope
2006-10-15 22:23:32
11. If you attempt to read the value of an undeclared variable, JavaScript will generate an error. If you assign a value to a variable that you have not declared with var, JavaScript will implicitly declare that variable for you. Note, however, that implicitly declared variables are always created as global variables, even if they are used within the body of a function. To prevent the creation of a global variable (or the use of an existing global variable) when you meant to create a local variable for use within a single function, you must always use the var statement within function bodies. It's best to use var for all variables, whether global or local. (The distinction between local and global variables is explored in more detail in the next section.)
//JavaScript: The Definitive Guide, 4th Edition -- 4.2.1 Repeated and Omitted Declarations
2006-10-15 22:00:53
10. Error Objects
ECMAScript v3 defines a number of classes that represent errors. The JavaScript interpreter "throws" an object of one of these types when a runtime error occurs. (See the throw and try statements in Chapter 6 for a discussion of throwing and catching errors.) Each error object has a message property that contains an implementation-specific error message. The types of predefined error objects are Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, and URIError. You can find out more about these classes in the core reference section of this book.
//JavaScript: The Definitive Guide, 4th Edition -- 3.11 Error Objects
2006-10-15 19:39:08
9. undefined
Another special value used occasionally by JavaScript is the undefined value returned when you use either a variable that has been declared but never had a value assigned to it, or an object property that does not exist. Note that this special undefined value is not the same as null.
Although null and the undefined value are distinct, the == equality operator considers them to be equal to one another. Consider the following:
my.prop == null
//JavaScript: The Definitive Guide, 4th Edition -- 3.8 undefined
2006-10-15 18:02:39
8. The way to really learn a new programming language is to write programs with it.
//JavaScript: The Definitive Guide, 4th Edition -- 1.10 Exploring JavaScript
2006-10-14 2:40:02
7. Both Netscape and Microsoft have made their JavaScript interpreters available to companies and programmers who want to embed them in their applications. Netscape's interpreter was released as open source and is now available through the Mozilla organization (see
http://www.mozilla.org/js/). Mozilla actually provides two different versions of the JavaScript 1.5 interpreter. One is written in C and is called "SpiderMonkey." The other is written in Java and, in a flattering reference to this book, is called "Rhino."
//JavaScript: The Definitive Guide, 4th Edition -- 1.4 JavaScript in Other Contexts
2006-10-14 1:13:44
6. 11.1.2 Explicit Type Conversions
Table 11-1 listed the automatic data type conversions that JavaScript performs. It is also possible to explicitly convert values from one type to another. JavaScript does not define a cast operator as C, C++, and Java do, but it does provide similar facilities for converting data values.
As of JavaScript 1.1 (and the ECMA-262 standard), Number( ) , Boolean( ), String( ), and Object( ) may be called as functions as well as being invoked as constructors. When invoked in this way, these functions attempt to convert their arguments to the appropriate type. For example, you could convert any value x to a string with String(x) and convert any value y to an object with Object(y).
There are a few other tricks that can be useful for performing explicit conversions. To convert a value to a string, concatenate it with the empty string:
var x_as_string = x + "";
To force a value to a number, subtract zero from it:
var x_as_number = x - 0;
And to force a value to boolean, use the ! operator twice:
var x_as_boolean = !!x;
Because of JavaScript's tendency to automatically convert data to whatever type is required, explicit conversions are usually unnecessary. They are occasionally helpful, however, and can also be used to make your code clearer and more precise.
//JavaScript: The Definitive Guide, 4th Edition -- 11.1 Data Type Conversion
2006-10-12 12:36:23
5. Each RegExp object has five properties. The source property is a read-only string that contains the text of the regular e-xpression. The global property is a read-only boolean value that specifies whether the regular e-xpression has the g flag. The ignoreCase property is a read-only boolean value that specifies whether the regular e-xpression has the i flag. The multiline property is a read-only boolean value that specifies whether the regular e-xpression has the m flag. The final property is lastIndex, a read-write integer. For patterns with the g flag, this property stores the position in the string at which the next search is to begin. It is used by the exec( ) and test( ) methods, as described in the previous section.
//JavaScript: The Definitive Guide, 4th Edition -- 10.3.2 RegExp Instance Properties
2006-10-9 21:23:26
4. the RegExp constructor. search( ) does not support global searches -- it ignores the g flag of its regular e-xpression argument.
//JavaScript: The Definitive Guide, 4th Edition -- 10.2 String Methods for Pattern Matching
2006-10-9 19:56:40
3. We've seen the . operator used to access the properties of an object. It is also possible to use the [] operator, which is more commonly used with arrays, to access these properties. Thus, the following two JavaScript e-xpressions have the same value:
object.property
object["property"]
//JavaScript: The Definitive Guide, 4th Edition -- 8.6 Objects as Associative Arrays
2006-10-9 14:45:13
2. The typeof Operator
typeof is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string, or boolean value. It evaluates to "object" for objects, arrays, and (surprisingly) null. It evaluates to "function" for function operands and to "undefined" if the operand is undefined.
//JavaScript: The Definitive Guide, 4th Edition -- 5.10.2 The typeof Operator
1. JavaScript strings (and JavaScript arrays, as we'll see later) are indexed starting with zero.
---/---------------------------------------------------------
小小心得
1. 花括弧定義 對(duì)象 元素, 方括弧定義 數(shù)組 元素. 2006-10-15 17:55:50
2. Javascript 正則表達(dá)式摘要
linenum
Javascript 與正則表達(dá)式 By shawl.qiu
語(yǔ)法方法:
5. str.split()
<script type="text/javascript">
//<![CDATA[
var str=' this , is, a, text';
document.write(str.split(/\s*,\s*/));
document.write('<br/>');
document.write(str.split(/\s*,\s*/).join());
//]]>
</script>
4. str.match()
<script type="text/javascript">
//<![CDATA[
var str=' This is a test. ';
document.write(str.match(/\w+/).join());
document.write('<br/>');
document.write(str.match(/\w+/g).join());
//]]>
</script>
3. str.replace()
<script type="text/javascript">
//<![CDATA[
var str=' This is a test. ';
document.write(str.replace(/^(\s+)|(\s+)$/,'----------'));
document.write('<br/>');
document.write(str.replace(/^(\s+)|(\s+)$/g,'----------'));
//]]>
</script>
2. str.search()
<script type="text/javascript">
//<![CDATA[
var str=' This is a test. ';
document.write(str.search(/this/i));
//]]>
</script>
1. 子匹配
<script type="text/javascript">
//<![CDATA[
var str=' this is a test '
document.write(str.match(/(is+).*?\1/)[0]);
//]]>
</script>
0. 創(chuàng)建正則表達(dá)式模式
0.1 new RegExp()
<script type="text/javascript">
//<![CDATA[
var str=' this is a test '
var re=new RegExp('\\w+','g');
document.write(str.match(re));
//]]>
</script>
-1. re.exec(str)
<script type="text/javascript">
//<![CDATA[
var str=' this is a test '
var pt=/this|test/g;
var report
while((report=pt.exec(str))!=null){
document.write(('match: ').bold()+report[0].fontcolor('red')+'<br/>');
document.write(('match index: ').bold()+(report.index+'').fontcolor('red')+'<br/>');
document.write(('match lastIndex: ').bold()+(pt.lastIndex+'').fontcolor('red')+'<p/>');
}
//]]>
</script>
-2. re.test(str)
<script type="text/javascript">
//<![CDATA[
var str=' this is a test ';
var re=/\d+/;
document.write(re.test(str));
var re=/\w+/;
document.write(re.test(str));
//]]>
</script>
---/----------------------------------------
摘要:
4. The String methods search( ) , replace( ), and match( ) do not use the lastIndex property as exec( ) and test( ) do. In fact, the String methods simply reset lastIndex( ) to 0. If you use exec( ) or test( ) on a pattern that has the g flag set and you are searching multiple strings, you must either find all the matches in each string, so that lastIndex is automatically reset to zero (this happens when the last search fails), or you must explicitly set the lastIndex property to 0 yourself. If you forget to do this, you may start searching a new string at some arbitrary position within the string rather than from the beginning. Finally, remember that this special lastIndex behavior occurs only for regular e-xpressions with the g flag. exec( ) and test( ) ignore the lastIndex property of RegExp objects that do not have the g flag.
//JavaScript: The Definitive Guide, 4th Edition -- 10.3.1 RegExp Methods for Pattern Matching
2006-10-20 18:10:36
3. match method
The match( ) method is the most general of the String regular e-xpression methods. It takes a regular e-xpression as its only argument (or converts its argument to a regular e-xpression by passing it to the RegExp( ) constructor) and returns an array that contains the results of the match. If the regular e-xpression has the g flag set, the method returns an array of all matches that appear in the string. For example:
"1 plus 2 equals 3".match(/\d+/g) // returns ["1", "2", "3"]
//JavaScript: The Definitive Guide, 4th Edition -- 10.2 String Methods for Pattern Matching
2006-10-20 17:23:08
2. search method
Strings support four methods that make use of regular e-xpressions. The simplest is search( ). This method takes a regular e-xpression argument and returns either the character position of the start of the first matching substring, or -1 if there is no match. For example, the following call returns 4:
"JavaScript".search(/script/i);
If the argument to search( ) is not a regular e-xpression, it is first converted to one by passing it to the RegExp constructor. search( ) does not support global searches -- it ignores the g flag of its regular e-xpression argument.
//JavaScript: The Definitive Guide, 4th Edition -- 10.2 String Methods for Pattern Matching
1. A number of punctuation characters have special meanings in regular e-xpressions. They are:
^ $ . * + ? = ! : | \ / ( ) [ ] { }
//JavaScript: The Definitive Guide, 4th Edition -- 10.1 Defining Regular Expressions
|