当前位置: 首页 > 图文教程 > 网络编程 > Javascript > Prototype Number对象 学习

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 Prototype Number对象 学习


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 398 ::
收藏到网摘: n/a

这个对象提供一些操作数值类型的工具函数
复制代码 代码如下:

Object.extend(Number.prototype, (function() {
//返回十六进制颜色之
function toColorPart() {
return this.toPaddedString(2, 16);
}
//返回连续的下一个数值
function succ() {
return this + 1;
}
//连续执行某个操作
function times(iterator, context) {
$R(0, this, true).each(iterator, context);
return this;
}
//返回固定长度的字符串,前面补0
function toPaddedString(length, radix) {
var string = this.toString(radix || 10);
return '0'.times(length - string.length) + string;
}
function toJSON() {
return isFinite(this) ? this.toString() : 'null';
}
function abs() {
return Math.abs(this);
}
function round() {
return Math.round(this);
}
function ceil() {
return Math.ceil(this);
}
function floor() {
return Math.floor(this);
}
return {
toColorPart: toColorPart,
succ: succ,
times: times,
toPaddedString: toPaddedString,
toJSON: toJSON,
abs: abs,
round: round,
ceil: ceil,
floor: floor
};
})());

这里简单介绍几个prototype扩展的方法。
times方法:
看一下示例
复制代码 代码如下:

var s = '';
(5).times(function(n) { s += n; });
alert(s);
// -> '01234'
//函数原型:times(iterator) -> Number,基本就是连续执行N次iterator方法,并且传给iterator的第一个参数为0~N-1
/*
这里注意一下调用方法时的写法:5要加上括号,否则直接写5.times,语法会有错误。因为5后面的点会被当成小数点解析,而小数点后面跟字符串会有语法错误。
还可以有令一种写法:5['times'](function(n) { s += n; });
其实这里的5和Number的关系就相当于C#里面int和Integer个关系差不多
*/

toJSON方法:

这个方法里面的isFinite(number)是JavaScript提供的全局方法:

假如 number 不是 NaN 、负无穷或正无穷,那么 isFinite 方法将返回 true 。 假如是这三种情况,函数返回 false 。

剩下方法就不多解释了,太简单了,给几个示例看看就完了:

复制代码 代码如下:

(5).succ()
// -> 6
$A($R(1, 5)).join('')
// -> '12345'
(128).toColorPart()
// -> '80'
(10).toColorPart()
// -> '0a'
(13).toPaddedString(4); // -> '0013'
(13).toPaddedString(2); // -> '13'
(13).toPaddedString(1); // -> '13'
(13).toPaddedString(4, 16) // -> '000d'
(13).toPaddedString(4, 2); // -> '1101'