学习JavaScript王者归来_02

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<html>
    <head>
        <title></title>
        <script>
            function ArrayList(array) {
                this._arr = typeof(array) = "string" ? array.split(",") : array;
            }
 
            //定义一个$each函数,这个函数接受一个闭包作为参数
            ArrayList.prototype.$each = function(closure) {
                var ret = [];
                for(var i = 0; i < this._arr.length; i++) {
                    ret.push(closure.call(this, this._arr[i]));
                }
 
                return ret;
            }
 
            ArrayList.prototype.add = function(num) {
                return this.$each(function(a) {return parseFloat(a) + parseFloat(num)});
            }
 
            ArrayList.prototype.multiply = function(factor) {
                return this.$each(function(a) {return parseFloat(a) * parseFloat(factor)});
            }
        </script>
    </head>
    <body>
        <input id = "list" type = "text" value = "1,2,3,4" />
        <input id = "num" type = "text" value = "2" />
        <input type = "button" value = "Add" onClick = "result.value = (new ArrayList(list.value)).add(num.value)" />
        <input type = "button" value = "Multiply" onClick = "result.value = (new ArrayList(list.value)).multiply(num.value)" />
        <br /><input type = "text" id = "result" />
    </body>
</html>

JS异常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
try {
    var n = prompt("Please enter a positive number");
    var f = factorial(n);
    alert(n + "! = " + f);
} catch(ex) {
    if(ex instanceof NonePositiveError) {
        aoert(ex.message);
    } else {
        throw(ex);
    }
} finally {
     
}
 
function NonePositiveError(n) {
    n = n || "";
    this.message = "";
}
 
NonePositiveError.prototype = new Error();
 
function factorial(n) {
    n = parseInt(n);
    if(isNaN(n)) {
        throw(new TypeError());
    } else if(n <= 0) {
        throw(new NonePositiveError(n));
    } else {
        return n <= 1 ? 1 : n * factorial(n - 1);
    }
}

  

学习JavaScript王者归来_02,布布扣,bubuko.com

学习JavaScript王者归来_02

上一篇:《深入Java虚拟机学习笔记》- 第14章 浮点运算


下一篇:Mod_python: The Long Story