這樣的代碼在javascript是正確的因?yàn)閖avascript 并沒有使用強(qiáng)類型,而是使用了一個(gè)寬松的類型定義,當(dāng)定義變量時(shí)賦值的類型是字符串型,使用中也可以給變量賦予整型的值。javascript會(huì)自動(dòng)轉(zhuǎn)換變量的類型。
confirm()
alert()函數(shù)純粹是彈出一個(gè)對(duì)話框,該對(duì)話框中只有一個(gè)“確定”按鈕。如以下代碼:
<script>
?????str_a="<b>BBBBBB</b>";
??? ?str_b="AAA";
???? alert(str_a+str_b);
</script>
該段代碼彈出的內(nèi)容是不會(huì)轉(zhuǎn)碼的,在所有對(duì)話框中,內(nèi)容都只是文件。并不解析成HTML代碼的。
prompt()函數(shù),用于接收用戶的輸出,彈出框中包含兩個(gè)參數(shù)一個(gè)是提示語言,一個(gè)是在框架窗體中的文件輸入框默認(rèn)值,格式如下:prompt(msg,"");
這是一個(gè)關(guān)于promt函數(shù)的例程:
???????<script?language?=?"JavaScript">
1???????????var?name=prompt("What?is?your?name?",?"");
2???????????document.write("<br>Welcome?to?my?world!?"
???????????????+?name?+?".</font><br>");
3???????????var?age=prompt("Tell?me?your?age.",?"Age");
4???????????if?(?age?==?null){????//?If?user?presses?the?cancel?button
5??????????????alert("Not?sharing?your?age?with?me");
6???????????}
????????????else{
7??????????????alert(age?+?"?is?young");
????????????}
8???????????alert(prompt("Where?do?you?live??",?""));
????????</script>
cofirm對(duì)話框,是用于讓用戶確認(rèn)回答問題,該類型的對(duì)話框通常用"確定","取消" 等按鈕.當(dāng)用戶單擊"確定"按鈕就返回true,單擊"取消"按鈕返回false,該函數(shù)只需要一個(gè)參數(shù),用戶提示要確認(rèn)的信息.
????????<script?language?=?"JavaScript">
????????????document.clear???//?Clears?the?page
1???????????if(confirm("Are?you?really?OK?")?==?true){
2??????????????alert("Then?we?can?proceed!");
????????????}
????????????else{
3??????????????alert("We'll?try?when?you?feel?better??");
????????????}
????????</script>
操作符
其實(shí)和C語言的操作差不多,主要不同的就是類型轉(zhuǎn)換,如果一個(gè)數(shù)字型與一個(gè)字符型相加,那么javascript 會(huì)自動(dòng)把數(shù)字型轉(zhuǎn)換成字符型,字符型字符串使用"= ="進(jìn)行比較是區(qū)分大小寫的。操作符的種類也和C語言差不多一樣,就是詳細(xì)列舉了。javascript提供了三種函數(shù)來顯示的實(shí)現(xiàn)原始類型轉(zhuǎn)換。
String();
Number();
Boolean();
????script?language="JavaScript">
1???????var?num1?=?prompt("Enter?a?number:?","");
????????var?num2?=?prompt("Enter?another?number:?","");
2???????var?result?=?Number(num1)?+?Number(num2);
????????????//?Convert?strings?to?numbers
3???????alert("Result?is?"+?result);
4???????var?myString=String(num1);
5???????result=myString?+?200;??//?String?+?Number?is?String
6???????alert("Result?is?"+?result);???//?Concatenates?200?to?the
????????????????????????????????????????//?result;?displays?20200
7???????????alert("Boolean?result?is?"+?Boolean(num2));??//?Prints?true
????</script>
parseInt(String)是將vstr轉(zhuǎn)換成整數(shù),
parseFloat(String)是將一字符串轉(zhuǎn)換成實(shí)數(shù)
eval(String)是將字符串轉(zhuǎn)換成數(shù)字值
eval("(22+66)/4") ,這表達(dá)式運(yùn)算的結(jié)果自然是22了,再參考下面代碼
????<script?language="JavaScript">
1???????var?str="5?+?4";
2???????var?num1?=?eval(str);
3???????var?num2?=?eval(prompt("Give?me?a?number?",?""));
4???????alert(num1?+?num2);
????</script>
條件判斷
任何語言都有自己的判斷語句javascript的條件控制語法和C差不多
if (condition){
?? statements
}
if (age >8){
?? alert("xxxx");
}
if (condition){
statements1;
}
else{
statements2;
}
參考例子
1???<script?language=javascript>
????????<!--??Hiding?JavaScript?from?old?browsers
????????document.write("<h3>");
2???????var?age=prompt("How?old?are?you??","");
3???????if(?age?>=?55?){
4???????????document.write("You?pay?the?senior?fare!?");
5???????}
6???????else{
7???????????document.write("You?pay?the?regular?adult?fare.?");
????????}
????????document.write("</h3>");
????????//-->
8???</script>
switch語句
6.2 ConditionalsConditional constructs control the flow of a program. If a condition is true, the program will execute a block of statements and if the condition is false, flow will go to an alternate block of statements. Decision-making constructs (if, else, switch) contain a control expression that determines whether a block of expressions will be executed. If the condition after the if is met, the result is true, and the following block of statements is executed; otherwise the result is false and the block is not executed. FORMAT if (condition){
statements;
}
Example: if ( age > 21 ){
alert("Let's Party!");
}
The block of statements (or single statement) is enclosed in curly braces. Normally, statements are executed sequentially. If there is only one statement after the conditional expression, the curly braces are optional. 6.2.1 if/else"You better pay attention now, or else . . . " Ever heard that kind of statement before? JavaScript statements can be handled the same way with the if/else branching construct. This construct allows for a two-way decision. The if evaluates the expression in parentheses, and if the expression evaluates to true, the block after the opening curly braces is executed; otherwise the block after the else is executed. FORMAT if (condition){
statements1;
}
else{
statements2;
}
Example: if ( x > y ){
alert( "x is larger");
}
else{
alert( "y is larger");
}
Example 6.1 <html>
<head>
<title>Conditional Flow Control</title>
</head>
<body>
1 <script language=javascript>
<!-- Hiding JavaScript from old browsers
document.write("<h3>");
2 var age=prompt("How old are you? ","");
3 if( age >= 55 ){
4 document.write("You pay the senior fare! ");
5 }
6 else{
7 document.write("You pay the regular adult fare. ");}
document.write("</h3>");
//-->
8 </script>
</body>
</html>
EXPLANATION 1 JavaScript program starts here. 2 The prompt dialog box will display the message "How old are you?". Whatever the user types into the box will be stored in the variable age. (See Figure 6.1.) 習(xí)資料\網(wǎng)頁設(shè)計(jì)資料\javascripte\Prentice%20Hall%20-%20JavaScript%20by%20Example%20-%202003.chm::/FILES/06fig01.jpg)
3, 4 If the value of the variable age is greater than or equal to 55, line 4 is executed. (See Figure 6.2.) 習(xí)資料\網(wǎng)頁設(shè)計(jì)資料\javascripte\Prentice%20Hall%20-%20JavaScript%20by%20Example%20-%202003.chm::/FILES/06fig02.jpg)
5 This closing curly brace closes the block of statements following the if expression. Because there is only one statement in the block, the curly braces are not required. 6, 7 The else statement, line number 7, is executed if the expression in line 3 is false. 8 This tag marks the end of the JavaScript program.
6.2.2 if/else if"If you've got $1, we can go to the Dollar Store; else if you've got $10, we could get a couple of movies; else if you've got $20 we could buy a CD . . . else forget it!" JavaScript provides yet another form of branching, the if/else if construct. This construct provides a multiway decision structure. FORMAT if (condition) {
statements1;
}
else if (condition) {
statements2;
}
else if (condition) {
statements3;
}
else{
statements4;
}
If the first conditional expression following the if keyword is true, the statement or block of statements following the expression are executed and control starts after the final else block. Otherwise, if the conditional expression following the if keyword is false, control branches to the first else if and the expression following it is evaluated. If that expression is true, the statement or block of statements following it are executed, and if false, the next else if is tested. All else ifs are tested and if none of their expressions are true, control goes to the else statement. Although the else is not required, it normally serves as a default action if all previous conditions were false. Example 6.2 <html>
<head>
<title>Conditional Flow Control</title>
</head>
<body>
1 <script language=javascript>
<!--
document.write("<H2>");
2 var age=eval( prompt("How old are you? ",""));
3 if( age > 0 && age <= 12 ){
4 document.write("You pay the child's fare. ");
}
5 else if( age > 12 && age < 60 ){
6 document.write("You pay the regular adult fare. ");
}
7 else {
document.write("You pay the senior fare! ");
}
document.write("</H2>");
//-->
8 </script></body></html>
EXPLANATION 1 JavaScript program starts here. 2 The prompt dialog box will display the message "How old are you? ". Whatever the user types into the box will be converted to a number by the eval() method and then stored in the variable age. 3, 4 If the value of the variable age is greater than 0 and age is also less than or equal to 12, then line 4 is executed. 5, 6 If the expression on line 3 is false, the JavaScript interpreter will test this line, and if the age is greater than 12 and also less than 60, the block of statements that follow will be executed. You can have as many else ifs as you like. 7 The else statement, line number 7, is executed if all of the previous expressions test false. This statement is called the default and is not required. 8 This tag marks the end of the JavaScript program.
6.2.3 switchThe switch statement is an alternative to if/else if conditional construct (commonly called a "case statement") and may make the program more readable when handling multiple options. It is supported in both Netscape Navigator and Internet Explorer. FORMAT switch (expression){
case label :
statement(s);
break;
case label :
statement(s);
break;
...
default : statement;
}
Example: switch (color){
case "red":
alert("Hot!");
break;
case "blue":
alert("Cold.");
break;
default:
alert("Not a good choice.");
break;
}
參考例子 |
????<script?language=javascript>
????<!--
1???var?color=prompt("What?is?your?color?","");
2???switch(color){
3???????case?"red":
????????????document.bgColor="color";
????????????document.write("Red?is?hot.");
4???????????break;
5???????case?"yellow":
????????????document.bgColor=color;
????????????document.write("Yellow?is?warm.");
6???????????break;
7???????case?"green":
????????????document.bgColor="lightgreen";
????????????document.write("Green?is?soothing.");
8???????????break;
9???????case?"blue":
????????????document.bgColor="#RRGGBB";
????????????document.write("Blue?is?cool.");
10??????????break;
11??????default:
????????????document.bgColor="white";
????????????document.write("Not?available?today.?We'll?use?white");
12??????????break;
13??????}
????????//-->
????</script>
Loops(循環(huán))語句
循環(huán)語句有三類,分別是while,for ,do/while。
while語句格式
while(condition){
???? statements?;
??? increment/decrement counter;
}
do/while格式
do{
? statements ;
while(condition);
??<script?language="JavaScript">
????????document.write("<font?size='+2'>");
1???????var?i=0;
2???????do{
3???????????document.writeln(i);
4???????????i++;
5???????}?while?(?i?<?10?)
????</script>
For 循環(huán)語句是經(jīng)常用的
for(Expression1;Expression2;Expression3)
??? {statement(s);}
for (initialize; test; increment/decrement)
??? {statement(s);}
具體的就不寫了。
Function函數(shù)介紹
?? javascript函數(shù)經(jīng)常用,但卻不懂怎么介紹,我覺得只要記錄js的函數(shù)是地址傳遞就可以了,就有函數(shù)可以作為對(duì)象的方法 .函數(shù)中可以有return 語句,也可以沒有。
Object介紹
對(duì)象的訪問通過“.”來執(zhí)行,與java一樣。
對(duì)象定義:
1、帶參數(shù)的對(duì)象定義
????? var obj=new Object(parameter1,parameter2);
2、不帶參數(shù)的定義
?????? var pet=new Object();
Object()函數(shù)是javascript自帶的默認(rèn)對(duì)象定義函數(shù)。參考如上例子:
????<html>
????<head><title>The?Object()?Constructor</title>
????<script?language?=?"javascript">
1???????var?pet?=?new?Object();
2???????alert(pet);
????</script>
????</head>
????<body></body>
????</html>
以上方法定義的是一個(gè)空的對(duì)象pet,因?yàn)閜et即沒有方法也沒有屬性。
pet.cat = new Object();
pet.dog = new Object();
pet.name="peidw";
為pet對(duì)象添加兩個(gè)對(duì)象和一個(gè)屬性,如:
????<script?language?=?"javascript">
????????var?pet?=?new?Object();
1???????pet.cat?=?new?Object();
2???????pet.cat.name?=?"Sneaky";
????????pet.cat.color?=?"yellow";
????????pet.cat.size?=?"fat";
????????pet.cat.attitude?=?"stuck?up";
????</script>
這是一個(gè)為對(duì)象添加對(duì)象和屬性的例子了。
用戶自定義
生成一個(gè)對(duì)象的方法如下
var car = new Object();
var friends = new Array("Tom", "Dick", "Harry");
var now= new Date("July 4, 2003");
以下是一個(gè)對(duì)象定義和使用例子:
???<html>
????<head><title>User-defined?objects</title>
1???????<script?language?=?"javascript">
2???????????var?toy?=?new?Object();???//?Create?the?object
3???????????toy.name?=?"Lego";??????//?Assign?properties?to?the?object
????????????toy.color?=?"red";
????????????toy.shape?=?"rectangle";
4???????</script>
????</head>
????<body?bgcolor="lightblue">
5???????<script?language?=?"javascript">
6???????????document.write("<b>The?toy?is??a?"?+?toy.name?+?".");
7???????????document.write("<br>It?is?a?"?+?toy.color?+?"?"
???????????????????????????+?toy.shape+?".");
8???????</script>
????</body>
????</html>
使用函數(shù)創(chuàng)建對(duì)象,用戶可以把對(duì)象特性作為函數(shù)的參數(shù)構(gòu)造對(duì)象,參考以下代碼:
???<script?language?=?"javascript">
1???????function?book(title,?author,?publisher){
????????//?Defining?properties
2???????????this.title?=?title;
3???????????this.author?=?author;
4???????????this.publisher?=?publisher;
5???????}
????</script>
????<body?bgcolor="lightblue"></body>
????<script?language?=?"javascript">
6???????var?myBook?=?new?book("JavaScript?by?Example",
??????????????????????????????"Ellie",?"Prentice?Hall");
7???????document.writeln("<b>"??+?myBook.title?+
?????????????????????????"<br>"?+?myBook.author?+
?????????????????????????"<br>"?+?myBook.publisher
????????????);
????</script>
以上例子中,我們并沒有給對(duì)象添加方法.
<body>fdgds
????<%out.println("ABCDEF");?%>
????<script?language="javascript"?type="text/javascript">
????????function?person(name,age,sex){
????????????this.name=name;
????????????this.age=age;
????????????this.sex=sex;
????????}
????????function?showName(){
????????????alert(this.name);
????????}
????????var?per=new?person("peidw",29,"男");
????????per.showname=showName;??//給對(duì)象定義方法
????????document.write(per.name+"?"+per.age+"?"+per.sex);
????????per.showname();
????</script>
以上代碼是生成對(duì)象以后再給對(duì)象創(chuàng)建了一個(gè)方法,通常我們構(gòu)造對(duì)象時(shí)就就已經(jīng)定義好了方法,參考以下例程:
????<html>
????<head><title>User-defined?objects</title>
????<script?language?="javascript">
1???????function?book(title,?author,?publisher){???//?Receiving
???????????????????????????????????????????????????//?parameters
2???????????this.pagenumber=0;??????//?Properties
????????????this.title?=?title;
????????????this.author?=?author;
????????????this.publisher?=?publisher;
3???????????this.uppage?=?pageForward;???//?Assign?function?name?to
?????????????????????????????????????????//?a?property
4???????????this.backpage?=?pageBackward;
????????}
5???????function?pageForward(){???//?Functions?to?be?used?as?methods
????????????this.pagenumber++;
????????????return?this.pagenumber;
????????}
6???????function?pageBackward(){
????????????this.pagenumber--;
????????????return?this.pagenumber;
????????}
????</script>
????</head>
????<body?bgcolor="lightblue">
????<script?language?=?"javascript">
7???????var?myBook?=?new?book("JavaScript?by?Example",?"Ellie",
??????????????????????????????"Prentice?Hall"?);???//?Create?new?object
8???????myBook.pagenumber=5;
9???????document.write(?"<b>"+?myBook.title?+
????????????????????????"<br>"?+?myBook.author?+
????????????????????????"<br>"?+?myBook.publisher?+
????????????????????????"<br>Current?page?is?"?+?myBook.pagenumber?);
????????document.write("<br>Page?forward:?"?);
10??????for(i=0;i<3;i++){
11??????????document.write("<br>"?+?myBook.uppage());
????????????//?Move?forward?a?page
????????}
????????document.write("<br>Page?backward:?");
????????for(;i>0;?i--){
12??????????document.write("<br>"?+?myBook.backpage());
????????????//?Move?back?a?page
????????}
????</script>
????</body>
????</html>
對(duì)象操作
1 、關(guān)鍵字“with”
????當(dāng)使用with(obj)函數(shù)時(shí)在with語句內(nèi)就不需要使用this.propeterty的方式來輸出對(duì)象的屬性如以下例子:
?
????<script?language="javascript"?type="text/javascript">
????????function?person(name,age,sex){
????????????this.name=name;
????????????this.age=age;
????????????this.sex=sex;
????????????this.show=showperson;
????????}
????????function?showperson(){
????????????with(this){
????????????????var?str=name+"-"+age+"-"+sex;
????????????????alert(str);
????????????}
????????}
????????var?per=new?person("peidw",125,"男");
????????per.show(per);
????</script>
“for/in loop”關(guān)鍵字
用來遍歷對(duì)象的屬性和數(shù)組無素
????<script?language="javascript"?type="text/javascript">
????????function?person(name,age,sex){
????????????this.name=name;
????????????this.age=age;
????????????this.sex=sex;
????????????this.show=showperson;
????????}
????????function?showperson(){
????????????with(this){
????????????????var?str=name+"-"+age+"-"+sex;
????????????????alert(str);
????????????}
????????}
????????function?showProps(obj){
????????????var?result="";
????????????for(var?prop?in?obj){
????????????????result+=prop+"="+obj[prop];
????????????}
????????????alert(result);
????????}
????????var?per=new?person("peidw",125,"男");
????????per.show(per);
????????showProps(per);
????</script>
以上代碼通過以使用for in loop遍歷對(duì)象!
擴(kuò)展對(duì)象原型的使用
?javascript通過使用prototypes來執(zhí)行繼承,它可以給對(duì)象添加屬性或
例子:
???<script?language?=?"javascript">
????//?Customize?String?Functions
1???????function?uc(){
2???????????var?str=this.big();
3???????????return(?str.toUpperCase());
????????}
4???????function?lc(){
5???????????var?str=this.small();
6???????????return(?str.toLowerCase());
????????}
7???????String.prototype.bigUpper=uc;
8???????String.prototype.smallLower=lc;
9???????var?string="This?Is?a?Test?STRING.";
10??????string=string.bigUpper();
????????document.write(string+"<br>");
11??????document.write(string.bigUpper()+"<br>");
12??????document.write(string.smallLower()+"<br>");
????</script>
JavaScript內(nèi)核對(duì)象
數(shù)組對(duì)象
數(shù)組對(duì)象的下標(biāo)可以是非負(fù)整數(shù)或字符串類型,當(dāng)數(shù)組的下標(biāo)是字符串時(shí),數(shù)組就叫聯(lián)合數(shù)組了。
數(shù)組定義:
像變量一樣數(shù)組在使用前必須先定義,定義格式如下
var array_name = new Array();
這樣定義的數(shù)組叫不定長數(shù)組,var array_name = new Array(100);這樣定義的數(shù)組是定長的,預(yù)定包含100個(gè)元素,var array_name = new Array("red", "green", "yellow", 1 ,2, 3);這樣定義的數(shù)組里的數(shù)據(jù)已經(jīng)初始化好的數(shù)據(jù)。下面是一個(gè)數(shù)組例程
????<head><title>The?Array?Object</title>
????<h2>An?Array?of?Books</h2>
????????<script?language="JavaScript">
1???????????var?book?=?new?Array(6);???//?Create?an?Array?object
2???????????book[0]?=?"War?and?Peace";?//?Assign?values?to?its?elements
????????????book[1]?=?"Huckleberry?Finn";
????????????book[2]?=?"The?Return?of?the?Native";
????????????book[3]?=?"A?Christmas?Carol";
????????????book[4]?=?"The?Yearling";
????????????book[5]?=?"Exodus";
????????</script>
????</head>
????<body?bgcolor="lightblue">
????????<script?language="JavaScript">
????????????document.write("<h3>");
3???????????for(var?i?in?book){
4??????????????document.write("book["?+?i?+?"]?"+?book[i]??+?"<br>");
????????????}
????????</script>
????</body>
以上代碼中,當(dāng)時(shí)最添加book[6]?=?"Exodus";這行代碼,程序也不會(huì)報(bào)錯(cuò)。
對(duì)于數(shù)組的循環(huán)通常采用以下這種方式
????<script?language="JavaScript">
1???????var?years?=?new?Array(10);
2???????for(var?i=0;?i?<?years.length;?i++?){
3???????????years[i]=i?+?2000;
4???????????document.write("years["?+?i?+?"]?=?"+?years[i]
??????????????????????????????+?"<br>");
????????}
????</script>
數(shù)組屬性及方法
數(shù)組對(duì)象有以下屬性:
Table 9.1. Array object properties.
|
constructor | References the object's constructor |
length | Returns the number of elements in the array |
prototype | Extends the definition of the array by adding properties and methods |
數(shù)組對(duì)象有以下方法:
Table 9.2. Array methods.
|
concat() | 把一個(gè)數(shù)組追加到另一個(gè)數(shù)組后面 |
join() | |
pop() | 刪除并返回?cái)?shù)組的最后一個(gè)元素 |
push() | 在數(shù)組的最后面添加新元素 |
reverse() | Reverses the order of the elements in an array |
shift() | 不懂怎么翻譯 |
slice() | 數(shù)據(jù)分切,格式var new_ary=數(shù)組名.slice(1,2); |
sort() | Sorts an array alphabetically, or numerically |
splice() | 刪除特定位置的元素,或使用新元素替換特定位置元素 |
toLocaleString() | Returns a string representation of the array in local format |
toString() | Returns a string representation of the array |
unshift() | 不懂怎么翻譯 |
以下是俺自己亂寫的一個(gè)例子
????<script?language="javascript"?type="text/javascript">
????????var?ary_book=new?Array(6);
????????ary_book[0]="VC";
????????ary_book[1]="C++";
????????ary_book[2]="JAVA";
????????ary_book[3]="C";
????????ary_book[4]="Pascal";
????????ary_book[5]="VB";
????????ary_book[6]="ab";
????????var?ary_EE=new?Array("a","b");
????????document.write("ary_book="+ary_book);
????????ary_book=ary_book.concat(ary_EE);
????????document.write("<br>連接后"+ary_book);
????????var?return_str=ary_book.pop();
????????document.write("<br>執(zhí)行pop刪除-"+return_str+"-后="+ary_book);
????????ary_book.push("push?elementA","push?elementB");
????????document.write("<br>執(zhí)行pop刪除-"+return_str+"-后并執(zhí)行追加函數(shù)后"+ary_book);
????????var?new_ary=ary_book.slice(1,3);
????????document.write("<br>分切后數(shù)組new_ary="+new_ary);
????????new_ary.splice(1,2,"AA","BB","CC");
????????document.write("<br>數(shù)組接合后new_ary="+new_ary);
????</script>
==========輸出結(jié)果如下========================
ABCDEF
ary_book=VC,C++,JAVA,C,Pascal,VB,ab
連接后VC,C++,JAVA,C,Pascal,VB,ab,a,b
執(zhí)行pop刪除-b-后=VC,C++,JAVA,C,Pascal,VB,ab,a
執(zhí)行pop刪除-b-后并執(zhí)行追加函數(shù)后VC,C++,JAVA,C,Pascal,VB,ab,a,push elementA,push elementB
分切后數(shù)組new_ary=C++,JAVA
數(shù)組接合后new_ary=C++,AA,BB,CC
以上就是數(shù)組的常用屬性和方法的例子了.
Date對(duì)象
Date對(duì)象的構(gòu)造,Date對(duì)象的構(gòu)造和java差不多,提供了以下構(gòu)造函數(shù)來創(chuàng)建Date對(duì)象:
var?Date?=?new?Date();???//?The?new?constructor?returns?a?Date?object.
var?Date?=?new?Date("July?4,?2004,?6:25:22");
var?Date?=?new?Date("July?4,?2004");
var?Date?=?new?Date(2004,?7,?4,?6,?25,?22);
var?Date?=?new?Date(2004,?7,?4);
var?Date?=?new?Date(Milliseconds);
Date對(duì)象的屬性及方法
Table 9.3. Date object methods.
|
getDate | Returns the day of the month (1–31) |
getDay | Returns the day of the week (0–6); 0 is Sunday, 1 is Monday, etc. |
getFullYear | Returns the year with 4 digits |
getHours | Returns the hour (0–23) |
getMilliseconds | Returns the millisecond[*] |
getMinutes | Returns hours since midnight (0–23) |
getMonth | Returns number of month (0–11); 0 is January, 1 is February, etc. |
getSeconds | Returns the second (0–59) |
getTime | Returns number of milliseconds since January 1, 1970 |
getTimeZoneOffset | Returns the difference in minutes between current time on local computer and UTC (Universal Coordinated Time) |
getUTCDate() | Returns the day of the month[*] |
getUTDDay() | Returns the day of the week converted to universal time[*] |
get UTCFullYear() | Returns the year in four digits converted to universal time[*] |
getUTCHours() | Returns the hour converted to universal time[*] |
getUTCMilliseconds() | Returns the millisecond converted to universal time[*] |
parse() | Converts the passed-in string date to milliseconds since January 1, 1970 |
setDate(value) | Sets day of the month (1–31) |
setFullYear() | Sets the year as a four-digit number[*] |
setHours() | Sets the hour within the day (0–23) |
setHours(hr,min,sec,msec) | Sets hour in local or UTC time |
setMilliseconds | Sets the millisecond[*] |
setMinutes(min,sec, msec) | Sets minute in local time or UTC |
setMonth(month,date) | Sets month in local time |
setSeconds() | Sets the second |
setTime() | Sets time from January 1, 1970, in milliseconds |
setUTCdate() | Sets the day of the month in universal time |
setUTCFullYear() | Sets the year as a four-digit number in universal time[*] |
setUTCHours() | Sets the hour in universal time[*] |
setUTCMilliseconds() | Sets the millisecond in universal time[*] |
setUTCMinutes() | Sets the minute in universal time[*] |
setUTCMonth() | Sets the month in universal time[*] |
setUTCSeconds() | Sets the second in universal time[*] |
setYear() | Sets the number of years since 1900 (00–99) |
toGMTString() | Returns the date string in universal format |
toLocaleString | Returns string representing date and time based on locale of computer as 10/09/99 12:43:22 |
toSource | Returns the source of the Date object[*] |
toString | Returns string representing date and time |
toUTCString | Returns string representing date and time as 10/09/99 12:43:22 in universal time[*] |
UTC() | Converts comma-delimited values to milliseconds[*] |
valueOf() | Returns the equivalence of the Date object in milliseconds[*] |
至于以上方法的使用,就不用詳細(xì)解析了。
Math對(duì)象
這是一個(gè)用于數(shù)學(xué)運(yùn)算的javascript內(nèi)置對(duì)象,該對(duì)象用于高級(jí)的科學(xué)計(jì)算,如果是簡間的運(yùn)想我覺得沒必要使用,Math對(duì)象屬性表:?
Table 9.5. Math object properties.
|
Math.E | 2.718281828459045091 | Euler's constant, the base of natural logarithms |
Math.LN2 | 0.6931471805599452862 | Natural log of 2 |
Math.LN10 | 2.302585092994045901 | Natural log of 10 |
Math.LOG2E | 1.442695040888963387 | Log base-2 of E |
Math.Log10E | 0.4342944819032518167 | Log base-10 of E |
Math.PI | 3.14592653589793116 | Pi, ratio of the circumference of a circle to its diameter |
Math.SQRT1_2 | 0.7071067811865475727 | 1 divided by the quare root of 2 |
Math.SQRT2 | 1.414213562373985145 | Square root of 2 |
Math對(duì)象方法:
Table 9.6. Math object methods.
|
Math.abs(Number) | Returns the absolute (unsigned) value of Number |
Math.acos(Number) | Arc cosine of Number, returns result in radians |
Math.asin(Number) | Arc sine of Number, returns results in radians |
Math.atan(Number) | Arctangent of Number, returns results in radians |
Math.atan2(y,x) | Arctangent of y/x; returns arctangent of the quotient of its arguments |
Math.ceil(Number) | Rounds Number up to the next closest integer |
Math.cos(Number) | Returns the cosign of Number in radians |
Math.exp(x) | Euler's constant to some power (see footnote) |
Math.floor(Number) | Rounds Number down to the next closest integer |
Math.log(Number) | Returns the natural logarithm of Number (base E) |
Math.max(Number1, Number2) | Returns larger value of Number1 and Number2 |
Math.min(Number1, Number2) | Returns smaller value of Number1 and Number2 |
Math.pow(x, y) | Returns the value of x to the power of y(xy), where x is the base and y is the exponent |
Math.random() | Generates pseudorandom number between 0.0 and 1.0 |
Math.round(Number) | Rounds Number to the closest integer |
Math.sin(Number) | Arc sine of Number in radians |
Math.sqrt(Number) | Square root of Number |
Math.tan(Number) | Tangent of Number in radians |
Math.toString(Number) | Converts Number to string |
?What Is a Wrapper Object?
這句英文我想應(yīng)該翻譯成“什么是對(duì)象封裝”,對(duì)象封裝是面向?qū)ο笤O(shè)計(jì)的一種特性,有時(shí)我們需要對(duì)原始來型進(jìn)行封裝,如我們需要對(duì)實(shí)數(shù)格式化成某種樣式或精確到第幾位小數(shù)等等的。
Table 9.8. String object properties.
|
length | Returns the length of the string in characters |
prototype | Extends the definition of the string by adding properties and methods |
下面例子是以上兩個(gè)屬性的使用例程
????<script?language="javascript"?type="text/javascript">
????????document.write("字符串屬性例子<br>");
????????var?str=new?String("abcdDeF");
????????function?up(){
????????????return?this.toUpperCase();
????????}
????????String.prototype.lup=up;
????????document.write("str長度="+str.length+"<br>");
????????document.write("str內(nèi)容="+str+"<br>");
????????document.write("uper轉(zhuǎn)換后="+str.lup()+"<br>");
????????
????</script>
String處理方法表(區(qū)分大小寫的)
|
charAt(index) | 返回字符串中index位置的字符(從0開始計(jì)算index) |
charCodeAt(index) | 返回特定字符串中index位置的字符的Unicode 編碼 |
concat(string1, ..., stringn) | 字函數(shù)的參數(shù)字符串連起來 |
fromCharCode(codes) | 把編碼轉(zhuǎn)換成字符 |
indexOf(substr, startpos) | 從字符串中返回從startpos開始的substr子串的位置 |
lastIndexOf(substr, startpos) | 從字符串中返回從最后一次出現(xiàn)substr子串的位置 |
replace(searchValue, replaceValue) | 把字符串中searchvalue轉(zhuǎn)換成replaceValue |
search(regexp) | Searches for the regular expression and returns the index of where it was found |
slice(startpos, endpos) | 返回從starpos到endpos位置的字符串 |
split(delimiter) | 把字符串以delimiter為分鬲符的字符串?dāng)?shù)組 |
substr(startpos, endpos) | 返回一個(gè)串但不包括endpos |
toLocaleLowerCase() | Returns a copy of the string converted to lowercase |
toLocaleUpperCase() | Returns a copy of the string converted to uppercase |
toLowerCase() | Converts all characters in a string to lowercase letters |
toString() | Returns the same string as the source string |
toUpperCase() | Converts all characters in a string to uppercase letters |
valueOf | Returns the string value of the object |
不想寫例子好,方法太多。實(shí)際上也經(jīng)常用到吧..
數(shù)字對(duì)象The Number Object
定義格式:
var number = new Number(numeric value);
var number = Number(numeric value);
例子:
var n = new Number(65.7);
屬性:
Table 9.11. The Number object's properties.
|
MAX_VALUE | The largest representable number, 1.7976931348623157e+308 |
MIN_VALUE | The smallest representable number, 5e–324 |
NaN | Not-a-number value |
NEGATIVE_INFINITY | Negative infinite value; returned on overflow |
POSITIVE_INFINITY | Infinite value; returned on overflow |
prototype | Used to customize the Number object by adding new properties and methods |
方法:
Table 9.12. The Number object's methods.
|
toString() | Converts a number to a string using a specified base (radix) |
toLocaleString() | Converts a number to a string using local number conventions |
toFixed() | Converts a number to a string with a specified number of places after the decimal point |
toExponential() | Converts a number to a string using exponential notation and a specified number of places after the decimal point |
toPrecision() | Converts a number to a string in either exponential or fixed notation containing the specified number of places after the decimal point |
自寫的一個(gè)例子:
????<script?language="javascript"?type="text/javascript">
????????var?num1=20;
????????var?num2=new?Number(13);
????????var?num3=new?Number(25.36985);
????????document.write("<br>num1=20,基數(shù)為2轉(zhuǎn)換成字符串->"+num1.toString(2)+"<br>");
????????document.write("num1=20,基數(shù)為8轉(zhuǎn)換成字符串->"+num1.toString(8)+"<br>");
????????document.write("num1=13,基數(shù)為2轉(zhuǎn)換成字符串->"+num2.toString(2)+"<br>");
????????document.write("num3=25.16985,取整到2位小數(shù)->"+num3.toFixed(2)+"<br>");
????</script>
The Boolean Object(Boolean對(duì)象)
自
9.6 What Is a Wrapper Object?The primitive man wraps himself up in an animal skin to keep warm or to protect his skin. A primitive data type can also have a wrapper. The wrapper is an object bearing the same name as the data type it represents. For each of the primitive data types (string, number, and Boolean), there is a String object, a Number object, and a Boolean object. These objects are called wrappers and provide properties and methods that can be defined for the object. For example, the String object has a number of methods that let you change the font color, size, and style of a string; and the Number object has methods that allow you to format a number to a specified number of significant digits. Whether you use the object or literal notation to create a string, number, or Boolean, JavaScript handles the internal conversion between the types. The real advantage to the wrapper object is its ability to apply and extend properties and methods to the object, which in turn, will affect the primitive. 9.6.1 The String ObjectWe have used strings throughout this book. They were sent as arguments to the write() and writeln() methods, they have been assigned to variables, they have been concatenated, and so on. As you may recall, a string is a sequence of characters enclosed in either double or single quotes. The String object (starting with JavaScript 1.1) is a core JavaScript object that allows you to treat strings as objects. The String object is also called a wrapper object because it wraps itself around a string primitive, allowing you to apply a number of properties and methods to it. You can create a String object implicitly by assigning a quoted string of text to a variable, called a string primitive (see "Primitive Data Types" on page 31 of Chapter 3), or by explicitly creating a String object with the new keyword and the String() object constructor method. Either way, the properties and methods of the String object can be applied to the new string variable. FORMAT var string_name = "string of text";
var string_name = new String("string of text");
Example: var title="JavaScript by Example";
var title=new String("JavaScript by Example");
Example 9.19 <html><head><title>The String Object</title></head>
<body bgcolor=pink><font face="arial" size=+1>
<h2>Primitive and String Objects</h2>
<script language="JavaScript">
1 var first_string = "The winds of war are blowing.";
2 var next_string = new String("There is peace in the valley.");
3 document.write("The first string is of type<em> "+
typeof(first_string));
document.write(".</em><br>The second string is of type<em> "+
4 typeof(next_string) +".<br>");
</script>
</body>
</html>
EXPLANATION This is the literal way to assign a string to a variable, and the most typical way. The string is called a string primitive. It is one of the basic building blocks of the language, along with numbers and Booleans. All of the properties and methods of the String object behave the same way whether you create a String literal or a String object as shown next. For all practical purposes, both methods of creating a string are the same, though this one is the easiest. The String() constructor and the new keyword are used to create a String object. This is the explicit way of creating a string. The typeof operator demonstrates that the first string, created the literal, implicit way, is a String data type. The typeof operator demonstrates that this string, created with the String() constructor, is an object type. Either way, when properties and methods are applied to a string, it is treated as a String object. (See Figure 9.20.) 習(xí)資料\網(wǎng)頁設(shè)計(jì)資料\javascripte\Prentice%20Hall%20-%20JavaScript%20by%20Example%20-%202003.chm::/FILES/09fig20.jpg)
The Properties of the String ObjectThe string properties (see Table 9.8) describe the attributes of the String object. The most common string property is the length property, which lets you know how many characters there are in a string. The prototype property allows you to add your own properties and methods to the String object, that is, you can customize a string. Table 9.8. String object properties.|
length | Returns the length of the string in characters | prototype | Extends the definition of the string by adding properties and methods |
Example 9.20 <html><head><title>The String Object</title></head>
<body bgColor="lightblue">
<font face="arial" size=+1>
<h3>Length of Strings</h3>
<script language="JavaScript">
1 var first_string = "The winds of war are blowing.";var next_string = new String("There is peace in the valley.");
2 document.write("\""+first_string +"\" contains "+
first_string.length + " characters.");
3 document.write("<br>\""+ next_string+"\" contains "+
next_string.length+" characters.<br>");
document.write("<font size=-1><em>...not to imply that war is
equal to peace...<br>");
</script>
</body>
</html>
EXPLANATION Two strings are created, one the literal way (a string primitive) and the other with the constructor method (a String object). The length property is applied to the first string. When the property is applied to a literal string, it is temporarily converted to an object, and then after the operation, it is reverted back to a string primitive. The length property is applied to the second string, a String object. (It is just a coincidence that both strings are of the same length.) (See Figure 9.21.) 習(xí)資料\網(wǎng)頁設(shè)計(jì)資料\javascripte\Prentice%20Hall%20-%20JavaScript%20by%20Example%20-%202003.chm::/FILES/09fig21.jpg)
Example 9.21 <html><head><title>The Prototype Property</title>
<script language = "javascript">
// Customize String Functions
1 function ucLarge(){
var str=this.bold().fontcolor("white").toUpperCase().fontsize("22");
return( str);
}
2 String.prototype.ucL=ucLarge;
</script>
</head>
<body bgcolor=black><center>
<script language="JavaScript">
3 var string="Watch Your Step!!";
4 document.write(string.ucL()+"<br>");
</script>
<img src="high_voltage.gif">
</body></html>
EXPLANATION The ucLarge() function is defined. Its purpose is to generate and return an uppercase, bold, white font, with a point size of 22. The prototype property allows you to customize an object by adding new properties and methods. The name of the customized method is ucL, which is the name of a new method that will be used by the String object. It is assigned the name (without parentheses) of the function ucLarge(), that performs the method's actions and returns a value. A new string is created. The prototyped method, ucL(), is applied to the String object, str. It will modify the string as shown in the output in Figure 9.22. 習(xí)資料\網(wǎng)頁設(shè)計(jì)資料\javascripte\Prentice%20Hall%20-%20JavaScript%20by%20Example%20-%202003.chm::/FILES/09fig22.jpg)
String MethodsThere are two types of string methods: the string formatting methods that mimic the HTML tags they are named for, and the methods used to manipulate a string such as finding a position in a string, replacing a string with another string, making a string uppercase or lowercase, and the like. Table 9.9 lists methods that will affect the appearance of a String object by applying HTML tags to the string, for example, to change its font size, font type, and color. Using these methods is a convenient way to change the style of a string in a JavaScript program, much easier than using quoted HTML opening and closing tags. Table 9.9. String object (HTML) methods.|
String.anchor(Name) | <a name="Name">String</a> | String.big() | <big>String</big> | String.blink() | <blink>String</blink> | String.bold() | <b>String</b> | String.fixed() | <tt>String</tt> | String.fontcolor(color) | <font color="color">String</font> e.g., <font color="blue">String</font> | String.fontsize(size) | <font size="size">String</font> e.g., <font size="+2">String</font> | String.italics() | <i>String</i> | String.link(URL) | <a href="URL">String</a> e.g., <a >String</a> | String.small() | <small>String</small> | String.strike() | <strike>String</strike> (puts a line through the text) | String.sub() | <sub>String</sub> (creates a subscript) | String.sup() | <sup>String</sup> (creates a superscript) |
Example 9.22 <html>
<head><title>String object</title>
</head>
<body bgcolor="yellow">
<font size="+1" face="arial">
<h2>Working with String Objects:</h2>
<script language="JavaScript">
1 var str1 = new String("Hello world!"); // Use a String constructor
2 var str2 = "It's a beautiful day today.";
document.write(str1) + "<br>";
3 document.write(str1.fontcolor("blue")+"<br>");
4 document.write(str1.fontsize(8).fontcolor("red").bold()+"<br>");
5 document.write(str1.big()+ "<br>");
6 document.write("Good-bye, ".italics().bold().big() +
str2 + "<br>");
</script>
</body></html>
EXPLANATION 1 A String object is created with the String() constructor. 2 A string primitive is created the literal way. 3 The fontcolor() method is used to change the color of the string to blue. This method emulates the HTML tag, <font color="blue">. 4 The fontsize(), fontcolor(), and bold() methods are used as properties of the string. 5, 6 The HTML method is concatenated to the string "Good-bye, " causing it to be displayed in italic, bold, big text. (See Figure 9.23.) 習(xí)資料\網(wǎng)頁設(shè)計(jì)資料\javascripte\Prentice%20Hall%20-%20JavaScript%20by%20Example%20-%202003.chm::/FILES/09fig23.jpg)
There are a number of methods (see Table 9.10) provided to manipulate a string. Table 9.10. Methods for string manipulation.|
charAt(index) | Returns the character at a specified index position | charCodeAt(index) | Returns the Unicode encoding of the character at a specified index position | concat(string1, ..., stringn) | Concatenates string arguments to the string on which the method was invoked | fromCharCode(codes) | Creates a string from a comma-separated sequence of character codes | indexOf(substr, startpos) | Searches for first occurrence of substr starting at startpos and returns the startpos(index value) of substr | lastIndexOf(substr, startpos) | Searches for last occurrence of substr starting at startpos and returns the startpos (index value) of substr | replace(searchValue, replaceValue) | Replaces searchValue with replaceValue | search(regexp) | Searches for the regular expression and returns the index of where it was found | slice(startpos, endpos) | Returns string containing the part of the string from startpos to endpos | split(delimiter) | Splits a string into an array of words based on delimiter | substr(startpos, endpos) | Returns a subset of string starting at startpos up to, but not including, endpos | toLocaleLowerCase() | Returns a copy of the string converted to lowercase | toLocaleUpperCase() | Returns a copy of the string converted to uppercase | toLowerCase() | Converts all characters in a string to lowercase letters | toString() | Returns the same string as the source string | toUpperCase() | Converts all characters in a string to uppercase letters | valueOf | Returns the string value of the object |
Methods That Find a Position in a StringA substring is a piece of an already existing string; thus eat is a substring of both create and upbeat, and java is a substring of javascript. When a user enters information, you want to see if a certain pattern of characters exist, such as the @ in an e-mail address or a zip code in an address. JavaScript provides a number of methods to assist you in finding substrings. The indexOf() and the lastIndexOf() methods are used to find the first instance or the last instance of a substring within a larger string. They are both case sensitive. The first character in a string is at index value 0, just like array indices. If either of the methods finds the substring, it returns the position of the first letter in the substring. If either method can't find the pattern in the string, then a –1 is returned. Example 9.23 <html><head><title>Substrings</title>
</head>
<body bgcolor=lightgreen>
<font face="arial" size="+1">
Searching for an @ sign
<script language="JavaScript">
1 var email_addr=prompt("What is your email address? ","");
2 while(email_addr.indexOf("@") == -1 ){
3 alert( "Invalid email address.");
email_addr=prompt("What is your email address? ",""); }
document.write("<br>OK.<br>");
</script>
</body></html>
EXPLANATION The user is prompted for his e-mail address and the input is assigned to a string called email_addr. The loop expression uses the indexOf() String method to see if there is an @ symbol in the e-mail address. If there isn't, the indexOf() method returns –1 and the body of the loop is executed. If the indexOf() method didn't find the @ substring, the alert box appears and the user is prompted again (see Figures 9.24 and 9.25). The loop terminates when the user enters an e-mail address containing an @ sign. Of course, this is just a simple test for validating an e-mail address; more elaborate methods of validation are discussed in Chapter 13, "Regular Expressions and Pattern Matching." 習(xí)資料\網(wǎng)頁設(shè)計(jì)資料\javascripte\Prentice%20Hall%20-%20JavaScript%20by%20Example%20-%202003.chm::/FILES/09fig24.jpg)
習(xí)資料\網(wǎng)頁設(shè)計(jì)資料\javascripte\Prentice%20Hall%20-%20JavaScript%20by%20Example%20-%202003.chm::/FILES/09fig25.jpg)
Example 9.24 <html>
<head><title>String Manipulation</title></head>
</head>
<body>
<h2>Working with String Manipulation Methods</h2>
<script language="JavaScript">
function break_tag(){
document.write("<br>");
}
document.write("<h3>");
1 var str1 = new String("The merry, merry month of June...");
document.write("In the string:<em> "+ str1 );
2 document.write("</em> the first 'm' is at position " +
str1.indexOf("m"));
break_tag();
3 document.write("The last 'm' is at position " +
str1.lastIndexOf("m"));
break_tag();
4 document.write("<em>str1.substr(4,5)</em> returns<em> " +
str1.substr(4,5));
break_tag();
document.write(str1.toUpperCase());
document.write("</h3>");
</script>
</body>
</html>
習(xí)資料\網(wǎng)頁設(shè)計(jì)資料\javascripte\Prentice%20Hall%20-%20JavaScript%20by%20Example%20-%202003.chm::/FILES/09fig26.jpg)
Methods that Extract Substrings from a StringYou may have to do more than just find a substring within a string, you may need to extract that substring. For example, we found the @ in the e-mail address, now we may want to get just the user name or the server name or domain name. To do this, JavaScript provides methods such as splice(), split(), charAt(), substr(), and substring(). Example 9.25 <html><head><title>Extracting Substrings</title>
</head>
<body bgcolor=lightgreen>
<font face="arial" size="+1">
Extracting substrings
<font size="-1">
<script language="JavaScript">
1 var straddr = "DanielSavage@dadserver.org";
document.write("<br>His name is<em> " +
2 straddr.substr(0,6) + "</em>.<br>");
3 var namesarr = straddr.split("@" );
4 document.write( "The user name is<em> " + namesarr[0] +
"</em>.<br>");
5 document.write( "and the mail server is<em> " + namesarr[1] +
"</em>.<br>");
6 document.write( "The first character in the string is <em>" +
straddr.charAt(0)+ "</em>.<br>");
7 document.write( "and the last character in the string is <em>"
+ straddr.charAt(straddr.length - 1)
+ "</em>.<br>");
</script>
</body></html>
EXPLANATION A string is assigned an e-mail address. The substr() starts at the first character at position 0, and yanks 6 characters from the starting position. The substring is Daniel. The split() method creates an array, called namesarr, by splitting up a string into substrings based on some delimiter that marks where the string is split. This string is split using the @ sign as its delimiter. The first element of the array, namesarr[0], that is created by the split() method is DanielSavage, the user name portion of the e-mail address. The second element of the array, namesarr[1], that is created by the split() method is dadserver.org, the mail server and domain portion of the e-mail address. The charAt() method returns the character found at a specified position within a string; in this example, position 0. Position 0 is the first character in the string, a letter D. By giving the charAt() method the length of the string minus 1, the last character in the string is extracted, a letter g. (See Figure 9.27.) 習(xí)資料\網(wǎng)頁設(shè)計(jì)資料\javascripte\Prentice%20Hall%20-%20JavaScript%20by%20Example%20-%202003.chm::/FILES/09fig27.jpg)
Search and Replace MethodsIn word processing software you'll always find some mechanism to search for patterns in strings and to replace one string with another. JavaScript provides methods to do the same thing, using the String object. The search() method searches for a substring and returns the position where the substring is found first. The match() method searches a string for substrings and returns an array containing all the matches it found. The replace() method searches for a substring and replaces it with a new string. These methods are discussed again in Chapter 13, "Regular Expressions and Pattern Matching," in more detail. Example 9.26 <html><head><title>Search and Replace</title>
</head>
<body bgcolor=lightgreen>
<font face="arial" size="+1">
Search and Replace Methods<br>
<font size="-1">
<script language="JavaScript">
1 var straddr = "DanielSavage@dadserver.org";
document.write( "The original string is "+ straddr + "<br>");
document.write( "The new string is "+
2 straddr.replace("Daniel","Jake")+"<br>");
3 var index=straddr.search("dad");
document.write("The search() method found \"dad\" at
position "+ index +"<br>");
4 var mysubstr=straddr.substr(index,3);
document.write("After replacing \"dad\" with \"POP\" <br>");
5 document.write(straddr.replace(mysubstr,"POP")+"<br>");
</script>
</body></html>
EXPLANATION An e-mail address is assigned to the string variable straddr. The replace() method takes two arguments, the search string and the replacement string. If the substring Daniel is found, it is replaced with Jake. The search() method takes a subtring as its argument and returns the first position where a substring is found in a string. In this example the substring dad is searched for in the string DanielSavage@dadserver.org and is found at position 13. The substr() method returns the substring found at position 13, 3 in the string, DanielSavage@dadserver.org: dad. The substring dad is replaced with POP in the string. (See Figure 9.28.) 習(xí)資料\網(wǎng)頁設(shè)計(jì)資料\javascripte\Prentice%20Hall%20-%20JavaScript%20by%20Example%20-%202003.chm::/FILES/09fig28.jpg)
9.6.2 The Number ObjectNow that we've travelled this far in JavaScript, have you wondered how to format a floating-point number when you display it, as you can with the printf function in C or Perl? Well, the Number object, like the String object, gives you properties and methods to handle and customize numeric data. The Number object is a wrapper for the primitive numeric values (see Chapter 2, "Script Setup"), which means you can use a primitive number type or an object number type and JavaScript manages the conversion back and forth as necessary. The Number object was introduced in JavaScript 1.1. The Number() constructor takes a numeric value as its argument. If used as a function, without the new operator, the argument is converted to a primitive numeric value, and that number is returned; if it fails, NaN is returned. The Number object has a number of properties and methods, as listed in Tables 9.11 and 9.12. FORMAT var number = new Number(numeric value);
var number = Number(numeric value);
Example: var n = new Number(65.7);
Table 9.11. The Number object's properties.|
MAX_VALUE | The largest representable number, 1.7976931348623157e+308 | MIN_VALUE | The smallest representable number, 5e–324 | NaN | Not-a-number value | NEGATIVE_INFINITY | Negative infinite value; returned on overflow | POSITIVE_INFINITY | Infinite value; returned on overflow | prototype | Used to customize the Number object by adding new properties and methods |
Table 9.12. The Number object's methods.|
toString() | Converts a number to a string using a specified base (radix) | toLocaleString() | Converts a number to a string using local number conventions | toFixed() | Converts a number to a string with a specified number of places after the decimal point | toExponential() | Converts a number to a string using exponential notation and a specified number of places after the decimal point | toPrecision() | Converts a number to a string in either exponential or fixed notation containing the specified number of places after the decimal point |
????<script?language="javascript"?type="text/javascript"> ????????var?num1=20; ????????var?num2=new?Number(13); ????????var?num3=new?Number(25.36985); ????????document.write("<br>num1=20,基數(shù)為2轉(zhuǎn)換成字符串->"+num1.toString(2)+"<br>"); ????????document.write("num1=20,基數(shù)為8轉(zhuǎn)換成字符串->"+num1.toString(8)+"<br>"); ????????document.write("num1=13,基數(shù)為2轉(zhuǎn)換成字符串->"+num2.toString(2)+"<br>"); ????????document.write("num3=25.16985,取整到2位小數(shù)->"+num3.toFixed(2)+"<br>"); ????</script>
FORM var object = new Boolean(value);
Example: var b1 = new Boolean(5);
var b2 = new Boolean(null); The Function Object函數(shù)對(duì)象 |