zl程序教程

您现在的位置是:首页 >  后端

当前栏目

PrototypeNumber对象学习

2023-06-13 09:14:11 时间
复制代码代码如下:

Object.extend(Number.prototype,(function(){

//返回十六进制颜色之    
functiontoColorPart(){
returnthis.toPaddedString(2,16);
}

//返回连续的下一个数值
functionsucc(){
returnthis+1;
}

//连续执行某个操作
functiontimes(iterator,context){
$R(0,this,true).each(iterator,context);
returnthis;
}

//返回固定长度的字符串,前面补0
functiontoPaddedString(length,radix){
varstring=this.toString(radix||10);
return"0".times(length-string.length)+string;
}

functiontoJSON(){
returnisFinite(this)?this.toString():"null";
}

functionabs(){
returnMath.abs(this);
}

functionround(){
returnMath.round(this);
}

functionceil(){
returnMath.ceil(this);
}

functionfloor(){
returnMath.floor(this);
}

return{
toColorPart:toColorPart,
succ:succ,
times:times,
toPaddedString:toPaddedString,
toJSON:toJSON,
abs:abs,
round:round,
ceil:ceil,
floor:floor
};
})());

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

vars="";
(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"