本站不再更新,欢迎光临 java开发技术网
随笔-230  评论-230  文章-8  trackbacks-0
javascript有三种基础类型,分别是:numeric,string,boolean
其中numeric又有实数型和整型。
变量名的定义和通常写JAVA程序一样。在JS中定义变量必需使用var <变量名>的方式来定义,如:
var  v_abc="abc";
v_abc=1215;

这样的代码在javascript是正确的因为javascript 并没有使用强类型,而是使用了一个宽松的类型定义,当定义变量时赋值的类型是字符串型,使用中也可以给变量赋予整型的值。javascript会自动转换变量的类型。

对话框
    在javascript中使用对话框用浏览用户进行对话、和问题回答。通常有以下三种方法建立对话框:
   
  • alert()

  • prompt()

  • confirm()

    alert()函数纯粹是弹出一个对话框,该对话框中只有一个“确定”按钮。如以下代码:
    <script>
         str_a="<b>BBBBBB</b>";
         str_b="AAA";
         alert(str_a+str_b);
    </script>
    该段代码弹出的内容是不会转码的,在所有对话框中,内容都只是文件。并不解析成HTML代码的。

    prompt()函数,用于接收用户的输出,弹出框中包含两个参数一个是提示语言,一个是在框架窗体中的文件输入框默认值,格式如下:prompt(msg,"");
    这是一个关于promt函数的例程:

           <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对话框,是用于让用户确认回答问题,该类型的对话框通常用"确定","取消" 等按钮.当用户单击"确定"按钮就返回true,单击"取消"按钮返回false,该函数只需要一个参数,用户提示要确认的信息.

            <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>

    操作符
    其实和C语言的操作差不多,主要不同的就是类型转换,如果一个数字型与一个字符型相加,那么javascript 会自动把数字型转换成字符型,字符型字符串使用"= ="进行比较是区分大小写的。操作符的种类也和C语言差不多一样,就是详细列举了。javascript提供了三种函数来显示的实现原始类型转换。
    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转换成整数,

    parseFloat(String)是将一字符串转换成实数

    eval(String)是将字符串转换成数字值
    eval("(22+66)/4") ,这表达式运算的结果自然是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 Conditionals

    Conditional 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.)

    Figure 6.1. The user is prompted for input.

    graphics/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.)

    Figure 6.2. If the age was entered was greater than 55, this message is displayed.

    graphics/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 switch

    The 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.[1]

    [1] Added to JavaScript 1.2 and supported by Internet Explorer 4.0+ and Netscape 4+.

    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(循环)语句
    循环语句有三类,分别是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 循环语句是经常用的
    for(Expression1;Expression2;Expression3)
        {statement(s);}
    for (initialize; test; increment/decrement)
        {statement(s);}
    具体的就不写了。
    Function函数介绍
       javascript函数经常用,但却不懂怎么介绍,我觉得只要记录js的函数是地址传递就可以了,就有函数可以作为对象的方法 .函数中可以有return 语句,也可以没有。

    Object介绍
    对象的访问通过“.”来执行,与java一样。
    对象定义:
    1、带参数的对象定义
          var obj=new Object(parameter1,parameter2);
    2、不带参数的定义
           var pet=new Object();
    Object()函数是javascript自带的默认对象定义函数。参考如上例子:

        <html>
        
    <head><title>The Object() Constructor</title>
        
    <script language = "javascript">
    1       var pet = new Object();
    2       alert(pet);
        
    </script>
        
    </head>
        
    <body></body>
        
    </html>

    以上方法定义的是一个空的对象pet,因为pet即没有方法也没有属性。
    pet.cat = new Object();
    pet.dog = new Object();
    pet.name="peidw";
    为pet对象添加两个对象和一个属性,如:

        <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>

    这是一个为对象添加对象和属性的例子了。
    用户自定义
    生成一个对象的方法如下
    var car = new Object();
    var friends = new Array("Tom", "Dick", "Harry");
    var now= new Date("July 4, 2003");
    以下是一个对象定义和使用例子:

       <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>

    使用函数创建对象,用户可以把对象特性作为函数的参数构造对象,参考以下代码:

       <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>

    以上例子中,我们并没有给对象添加方法.

    <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;  //给对象定义方法
            document.write(per.name+" "+per.age+" "+per.sex);
            per.showname();
        
    </script>

    以上代码是生成对象以后再给对象创建了一个方法,通常我们构造对象时就就已经定义好了方法,参考以下例程:

        <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>

    对象操作
    1 、关键字“with”
        当使用with(obj)函数时在with语句内就不需要使用this.propeterty的方式来输出对象的属性如以下例子:
     

        <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”关键字
    用来遍历对象的属性和数组无素

        <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遍历对象!

    扩展对象原型的使用
     javascript通过使用prototypes来执行继承,它可以给对象添加属性或
    例子:

       <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内核对象
    数组对象
    数组对象的下标可以是非负整数或字符串类型,当数组的下标是字符串时,数组就叫联合数组了。
    数组定义:
    像变量一样数组在使用前必须先定义,定义格式如下
    var array_name = new Array();
    这样定义的数组叫不定长数组,var array_name = new Array(100);这样定义的数组是定长的,预定包含100个元素,var array_name = new Array("red", "green", "yellow", 1 ,2, 3);这样定义的数组里的数据已经初始化好的数据。下面是一个数组例程

        <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>

    以上代码中,当时最添加book[6= "Exodus";这行代码,程序也不会报错。
    对于数组的循环通常采用以下这种方式

        <script language="JavaScript">
    1       var years = new Array(10);
    2       for(var i=0; i < years.length; i++ ){
    3           years[i]=+ 2000;
    4           document.write("years[" + i + "] = "+ years[i]
                                  
    + "<br>");
            }
        
    </script>

    数组属性及方法
    数组对象有以下属性:

    Table 9.1. Array object properties.

    Property

    What It Does

    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

    数组对象有以下方法:
    Table 9.2. Array methods.

    Method

    What It Does

    concat()

    把一个数组追加到另一个数组后面

    join()

    pop()

    删除并返回数组的最后一个元素

    push()

    在数组的最后面添加新元素

    reverse()

    Reverses the order of the elements in an array

    shift()

    不懂怎么翻译

    slice()

    数据分切,格式var new_ary=数组名.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()

    不懂怎么翻译

    以下是俺自己乱写的一个例子
        <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>执行pop删除-"+return_str+"-后="+ary_book);
            ary_book.push(
    "push elementA","push elementB");
            document.write(
    "<br>执行pop删除-"+return_str+"-后并执行追加函数后"+ary_book);
            
    var new_ary=ary_book.slice(1,3);
            document.write(
    "<br>分切后数组new_ary="+new_ary);
            new_ary.splice(
    1,2,"AA","BB","CC");
            document.write(
    "<br>数组接合后new_ary="+new_ary);
        
    </script>

    ==========输出结果如下========================
    ABCDEF ary_book=VC,C++,JAVA,C,Pascal,VB,ab
    连接后VC,C++,JAVA,C,Pascal,VB,ab,a,b
    执行pop删除-b-后=VC,C++,JAVA,C,Pascal,VB,ab,a
    执行pop删除-b-后并执行追加函数后VC,C++,JAVA,C,Pascal,VB,ab,a,push elementA,push elementB
    分切后数组new_ary=C++,JAVA
    数组接合后new_ary=C++,AA,BB,CC

    以上就是数组的常用属性和方法的例子了.
    Date对象
    Date对象的构造,Date对象的构造和java差不多,提供了以下构造函数来创建Date对象:

    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(20047462522);
    var Date = new Date(200474);
    var Date = new Date(Milliseconds);

    Date对象的属性及方法

    Table 9.3. Date object methods.

    Method

    What It Does

    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[*]


    至于以上方法的使用,就不用详细解析了。

    Math对象
    这是一个用于数学运算的javascript内置对象,该对象用于高级的科学计算,如果是简间的运想我觉得没必要使用,Math对象属性表: 
    Table 9.5. Math object properties.

    Property

    Value

    Description

    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对象方法:
    Table 9.6. Math object methods.

    Method

    Functionality

    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?
    这句英文我想应该翻译成“什么是对象封装”,对象封装是面向对象设计的一种特性,有时我们需要对原始来型进行封装,如我们需要对实数格式化成某种样式或精确到第几位小数等等的。

    Table 9.8. String object properties.

    Property

    What It Does

    length

    Returns the length of the string in characters

    prototype

    Extends the definition of the string by adding properties and methods

    下面例子是以上两个属性的使用例程
        <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内容="+str+"<br>");
            document.write(
    "uper转换后="+str.lup()+"<br>");
            
        
    </script>
    String处理方法表(区分大小写的)

    Method

    What it Does

    charAt(index)

    返回字符串中index位置的字符(从0开始计算index)

    charCodeAt(index)

    返回特定字符串中index位置的字符的Unicode 编码

    concat(string1, ..., stringn)

    字函数的参数字符串连起来

    fromCharCode(codes)

    把编码转换成字符

    indexOf(substr, startpos)

    从字符串中返回从startpos开始的substr子串的位置

    lastIndexOf(substr, startpos)

    从字符串中返回从最后一次出现substr子串的位置

    replace(searchValue, replaceValue)

    把字符串中searchvalue转换成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为分鬲符的字符串数组

    substr(startpos, endpos)

    返回一个串但不包括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

    不想写例子好,方法太多。实际上也经常用到吧..

    数字对象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.

    Property

    What It Describes

    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.

    Method

    What It Does

    toString()

    Converts a number to a string using a specified base (radix)

    toLocaleString()

    Converts a number to a string using local number conventions

    toFixed()[1]

    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,基数为2转换成字符串->"+num1.toString(2)+"<br>");
            document.write(
    "num1=20,基数为8转换成字符串->"+num1.toString(8)+"<br>");
            document.write(
    "num1=13,基数为2转换成字符串->"+num2.toString(2)+"<br>");
            document.write(
    "num3=25.16985,取整到2位小数->"+num3.toFixed(2)+"<br>");
        
    </script>
    The Boolean Object(Boolean对象)

    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 Object

    We 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

    1. 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.

    2. The String() constructor and the new keyword are used to create a String object. This is the explicit way of creating a string.

    3. The typeof operator demonstrates that the first string, created the literal, implicit way, is a String data type.

    4. 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.)

      Figure 9.20. Output from Example 9.19.

      graphics/09fig20.jpg

    The Properties of the String Object

    The 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.

    Property

    What It Does

    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

    1. Two strings are created, one the literal way (a string primitive) and the other with the constructor method (a String object).

    2. 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.

    3. 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.)

      Figure 9.21. Using the String object's length property. Output from Example 9.20.

      graphics/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

    1. The ucLarge() function is defined. Its purpose is to generate and return an uppercase, bold, white font, with a point size of 22.

    2. 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.

    3. A new string is created.

    4. 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.

      Figure 9.22. Using the String object's prototype property. Output from Example 9.21.

      graphics/09fig22.jpg

    String Methods

    There 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.

    Method

    Formats as HTML

    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 href="http://www.ellieq.com">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.)

    Figure 9.23. Properties of the String object are used to change its appearance and determine its size. Output from Example 9.22.

    graphics/09fig23.jpg

    There are a number of methods (see Table 9.10) provided to manipulate a string.

    Table 9.10. Methods for string manipulation.

    Method

    What it Does

    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 String

    A 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

    1. The user is prompted for his e-mail address and the input is assigned to a string called email_addr.

    2. 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.

    3. 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."

      Figure 9.24. Using the indexOf() String method.

      graphics/09fig24.jpg

      Figure 9.25. The user entered an e-mail address without the @ symbol.

      graphics/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>
    
    Figure 9.26. Output from Example 9.24.

    graphics/09fig26.jpg

    Methods that Extract Substrings from a String

    You 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

    1. A string is assigned an e-mail address.

    2. The substr() starts at the first character at position 0, and yanks 6 characters from the starting position. The substring is Daniel.

    3. 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.

    4. 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.

    5. 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.

    6. 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.

    7. 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.)

      Figure 9.27. The charAt(), split(), and substr() methods. Output from Example 9.25.

      graphics/09fig27.jpg

    Search and Replace Methods

    In 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

    1. An e-mail address is assigned to the string variable straddr.

    2. The replace() method takes two arguments, the search string and the replacement string. If the substring Daniel is found, it is replaced with Jake.

    3. 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.

    4. The substr() method returns the substring found at position 13, 3 in the string, DanielSavage@dadserver.org: dad.

    5. The substring dad is replaced with POP in the string. (See Figure 9.28.)

      Figure 9.28. The search() and replace() String methods. Output from Example 9.26.

      graphics/09fig28.jpg

    9.6.2 The Number Object

    Now 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.

    Property

    What It Describes

    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.

    Method

    What It Does

    toString()

    Converts a number to a string using a specified base (radix)

    toLocaleString()

    Converts a number to a string using local number conventions

    toFixed()[1]

    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,基数为2转换成字符串->"+num1.toString(2)+"<br>");
            document.write(
    "num1=20,基数为8转换成字符串->"+num1.toString(8)+"<br>");
            document.write(
    "num1=13,基数为2转换成字符串->"+num2.toString(2)+"<br>");
            document.write(
    "num3=25.16985,取整到2位小数->"+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函数对象
  • 属性表:
    Table 9.13. Properties of the Function object.

    Property

    What It Does

    length

    Returns the number of arguments that are expected to be passed (read only)

    prototype

    Allows the object to be customized by adding new properties and methods

    方法:
    Table 9.14. Methods of the Function object.

    Property

    What It Does

    apply()[*]

    Allows you to apply a method from one function to another

    call()

    Allows you to call a method from another object

    FORMAT

    var nameOfFunction = new Function (arguments, statements_as_string: }
    

    Example Function Definition:

    var addemUp = new Function ( "a", "b", "return a + b;" );
    

    Example Function Call:

    document.write(addemUp (10, 5));
    
        <script language="javascript" type="text/javascript">
            
    var fsum=new Function("a","b","return a+b;");
            document.write(
    "the sum="+fsum(5,10)+"<br>");
        
    </script>
    posted on 2006-11-07 23:09 有猫相伴的日子 阅读(987) 评论(0)  编辑  收藏 所属分类: javascirpt

    只有注册用户登录后才能发表评论。


    网站导航:
     
    本站不再更新,欢迎光临 java开发技术网