首页 > 代码库 > 学习JavaScript王者归来_02
学习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 = http://www.mamicode.com/ "1,2,3,4" /> <input id = "num" type = "text" value = http://www.mamicode.com/ "2" /> <input type = "button" value = http://www.mamicode.com/ "Add" onClick = "result.value = http://www.mamicode.com/(new ArrayList(list.value)).add(num.value)" /> <input type = "button" value = http://www.mamicode.com/ "Multiply" onClick = "result.value = http://www.mamicode.com/(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); } } |
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。