首页 > 编程语言 > 详细

学习JavaScript王者归来_02

时间:2014-05-14 23:46:16      阅读:588      评论:0      收藏:0      [点我收藏+]
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

原文:http://www.cnblogs.com/sibeta/p/3728715.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!