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