学习JavaScript王者归来_02
<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异常
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);
}
}

浙公网安备 33010602011771号