惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Engineering at Meta
Engineering at Meta
The GitHub Blog
The GitHub Blog
博客园_首页
T
The Blog of Author Tim Ferriss
H
Hackread – Cybersecurity News, Data Breaches, AI and More
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
腾讯CDC
I
InfoQ
量子位
J
Java Code Geeks
P
Proofpoint News Feed
有赞技术团队
有赞技术团队
Webroot Blog
Webroot Blog
Martin Fowler
Martin Fowler
D
Docker
F
Fortinet All Blogs
云风的 BLOG
云风的 BLOG
V
Vulnerabilities – Threatpost
罗磊的独立博客
P
Proofpoint News Feed
T
The Exploit Database - CXSecurity.com
Cyberwarzone
Cyberwarzone
P
Privacy & Cybersecurity Law Blog
Last Week in AI
Last Week in AI
爱范儿
爱范儿
The Hacker News
The Hacker News
S
SegmentFault 最新的问题
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 三生石上(FineUI控件)
V
V2EX
Simon Willison's Weblog
Simon Willison's Weblog
AI
AI
Y
Y Combinator Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
GbyAI
GbyAI
V
Visual Studio Blog
H
Heimdal Security Blog
S
Secure Thoughts
B
Blog RSS Feed
雷峰网
雷峰网
T
Tenable Blog
C
Check Point Blog
G
Google Developers Blog
大猫的无限游戏
大猫的无限游戏
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
A
About on SuperTechFans
Recent Commits to openclaw:main
Recent Commits to openclaw:main

博客园 - josson

JAVA写文件到FTP的两种方法(转) - josson - 博客园 Linux的一些命令 如何实时查看mysql当前连接数? (收藏)Turbo C 2.0、Borland C++库函数及用例 - josson (收藏)C库函数手册 MySQL的大小写敏感设置 ORACLE应用经验-表空间 Linux中通过locale来设置字符集 Oracle字符集问题总结 Oracle 表空间相关命令常识 定时执行的SQL脚本 ORACLE常识_关于SQLPLUS Axis开发之Stubs方式 Web Service 入门之常识 RMI入门 常用正则表达式 一些javascript脚本 文本模式启动linux vi 命令说明
JavaScript/Jscript核心语言对象扩充函数
josson · 2006-09-08 · via 博客园 - josson

一、对象函数的扩充和代码

扩充函数的对象包括ArrayStringDateNumberBoolean

Array对象扩充函数

函数名

参数

说明

indexOf

_value

返回数组中值等于参数_value的元素索引位置,如果没有返回-1

lastIndexOf

_value

返回数组中值等于参数_value的元素反向索引位置,如果没有返回-1

contains

_value

返回数组中是否存在值等于参数_value的元素,true为存在,false不存在

copy

拷贝数组到一个新数组中

insertAt

_value, i

插入参数值_value到参数i指定索引的位置上

insertBefore

_value, _invalue

插入参数值_value到数组中值等于参数_inValue的元素前

removeAt

i

删除索引位置为i的元素

remove

_value

删除值为_value的元素

String对象扩充函数

函数名

参数

说明

trim

返回去掉前后空白字符的字符串

lTrim

返回去掉左边的空白字符的字符串

rTrim

返回去掉右边的空白字符的字符串

lTrimZero

返回去掉左边的”0”字符的字符串

left

_leftNum

返回左边_leftNum个字符

right

_rightNum

返回右边_rightNum个字符

hasAlpha

判断字符串是否有Alpha字符(@#$等非数字字母字符)

isAlpha

判断字符串是否完全是Alpha字符

isLetter

判断字符串是否完全是字母字符

isFigure

判断字符串是否完全是数字字符

isDomainName

判断字符串是否是一个合法的域名字符串

isEmail

判断字符串是否是一个电子邮件地址

isHex

判断字符串是否是十六进制字符

isGuid

判断字符串是否是Guid

isInteger

_bitType

判断字符串是否可为指定_bitType类型的整型数(“64bit”||”32bit”||”16bit”)

isInt8

判断字符串是否可为int8的整型数

isInt16

判断字符串是否可为int16的整型数

isInt32

判断字符串是否可为int32的整型数

isInt64

判断字符串是否可为int64的整型数

toDate

将字符串转换成时间类型数值,能够转成合法Date的字符形如:yyyy-mm-dd or yyyy/mm/dd

toNumber

将字符串转换成为数字类型数值

Date对象扩充函数

函数名

参数

说明

getQuarter

返回时间的季度值

dateAdd

_timeInterval, _number

返回间隔_number量的时间,_timerInterval为间隔类型,分别有年(yyyy),月(mm),日(dd),时(h),分(m),秒(s),星期(ww)

formatDateTime

_nameFormate

返回时间的格式化字符串,_nameFormate为格式类型,此函数可参考vbs同名函数

isNaN

时间变量是否是合法的,true为非法变量,false为合法的。

Number对象扩充函数

函数名

参数

说明

abs

返回值的绝对值

acos

返回值以弧度为单位的反余弦

asin

返回值以弧度为单位的反正弦

atan

返回值以弧度为单位的反正切

atan2

_value

返回值与_value的商的反正切

ceil

返回大于等于值的下一个整数

cos

返回值的余弦

exp

返回值的欧拉常量

floor

返回小于值等于值的整数

log

返回值以e为底的自然对数

round

返回值四舍五入后的数

sin

返回值以弧度为单位的正弦

sqrt

返回值的平方根

isNaN

判断是否是一个合法的数值

tan

返回值以弧度为单位的正切

浏览器中上述对象扩充了两个消息提示函数alertcofirm,可以直接使用对象引用函数来弹出消息框。

代码部分:

-----------------------------------------------------------------------------------------------------------------------

Array.prototype.indexOf = function(_value){

         for(var i=0;i<this.length;i++)if(this[i]==_value)return i;

         return -1;

};

Array.prototype.lastIndexOf = function(_value){

         for(var i=this.length-1;i>=0;i--)if(this[i]==_value)return i;

         return -1;

};

Array.prototype.contains = function(_value){return this.indexOf(_value)!= -1;};

Array.prototype.copy = function(){return this.concat();};

Array.prototype.insertAt = function(_value,i){this.splice(i,0,_value);};

Array.prototype.insertBefore = function(_value,_inValue){

         var i=this.indexOf(_inValue);

         if(i== -1)this.push(_value);

         else this.splice(i,0,_value);

};

Array.prototype.removeAt = function(i){this.splice(i,1);};

Array.prototype.remove = function(_value){

         var i=this.indexOf(_value);

         if(i!= -1)this.splice(i,1);

};

String.prototype.trim = function(){return this.replace(/(^\s+)|\s+$/g,"");};

String.prototype.lTrim = function(){return this.replace(/(^\s+)/g,"")};

String.prototype.rTrim = function(){return this.replace(/(\s+$)/g,"")};

String.prototype.lTrimZero = function(){return this.replace(/(^0+)/g,"")};

String.prototype.left = function(_leftNum){return this.substr(0,_leftNum)};

String.prototype.right = function(_rightNum){return this.substr(this.length - _rightNum)};

String.prototype.hasAlpha = function(){

         var _checkAlpha = /[\/\\\.\*\+\?\|\(\)\{\}\[\]\-~`!@#$%^&_=:;"'<>,.]/;

         return(_checkAlpha.test(this));

};

String.prototype.isAlpha = function(){

         var _checkAlpha = /[^\/\\\.\*\+\?\|\(\)\{\}\[\]\-~`!@#$%^&_=:;"'<>,.]/;

         return(!_checkAlpha.test(this));

};

String.prototype.isLetter = function(){return(!(/\W/.test(this)||/\d/.test(this)));};

String.prototype.isFigure = function(){return(!/\D/.test(this));};

String.prototype.isDomainName = function(){return(!/[^\w-_\.]|^\.|\.$/.test(this));};

String.prototype.isEmail = function(){

         var _emailList = this.split("@");

         if(_emailList.length != 2)return false;

         return((!/[^\w-_]/.test(_emailList[0]))&&_emailList[1].isDomainName());

};

String.prototype.isHex = function(){return(!/[^\dABCDEFabcdef]/.test(this));};

String.prototype.isGuid = function(){

         if(this.left(1)!="{"||this.right(1)!="}")return false;

         var _hexNumberList = this.replace(/(^\{)|(\}$)/g,"").split("-");

         if(_hexNumberList.length!=5)return false;

         if(_hexNumberList[0].length!=8||!_hexNumberList[0].isHex())return false;

         if(_hexNumberList[1].length!=4||!_hexNumberList[1].isHex())return false;

         if(_hexNumberList[2].length!=4||!_hexNumberList[2].isHex())return false;

         if(_hexNumberList[3].length!=4||!_hexNumberList[3].isHex())return false;

         if(_hexNumberList[4].length!=12||!_hexNumberList[4].isHex())return false;

         return true;

};

String.prototype.isInteger = function(_bitType){

         var _limitValue = [];

         _limitValue["Upper"] = [];

         _limitValue["Lower"] = [];

         _limitValue["Upper"]["64bit"] = "9223372036854775807";

         _limitValue["Upper"]["32bit"] = "2147483647";

         _limitValue["Upper"]["16bit"] = "32767";

         _limitValue["Lower"]["64bit"] = "9223372036854775808";

         _limitValue["Lower"]["32bit"] = "2147483648";

         _limitValue["Lower"]["16bit"] = "32768";

         var _plus = "Upper";

         var _theValue = new String(this);

         if(_theValue.indexOf("-")==0){

                   _theValue = _theValue.substr(1,_theValue.length-1);

                   _plus = "Lower";

         }      

         if(!_theValue.isFigure())return false;

         if(_limitValue[_plus][_bitType].length < _theValue.length)return false;

         if(_limitValue[_plus][_bitType].length == _theValue.length){

                   for(var i=0;i<_limitValue[_plus][_bitType].length;i++){

                            if(_theValue.charAt(i) < _limitValue[_plus][_bitType].charAt(i))return true;

                   }

                   if(_limitValue[_plus][_bitType] != _theValue)return false;

         }

         return true;

};

String.prototype.isInt8 = function(){

         var _theValue = this.toNumber();

         if(_theValue.isNaN())return false;

         if(_theValue < 0 || _theValue > 255)return false;

         if(_theValue.toString() != this)return false;

         return true;

};

String.prototype.isInt16 = function(){return this.isInteger("16bit");};

String.prototype.isInt32 = function(){return this.isInteger("32bit");};

String.prototype.isInt64 = function(){return this.isInteger("64bit");};

String.prototype.toDate = function(){

         var _dateStr = this.trim().split(/\s/)[0];

         var _timeStr = (this.trim().split(/\s/)[1]?this.trim().split(/\s/)[1]:"1:1:1");

         var _dateSplitSymbol = /[\/\-,]/;

         var _timeSplitSymbol = /[:,]/;

         if(!_dateSplitSymbol.test(_dateStr))return new Date("x");

         var _SplitSymbol = _dateSplitSymbol.exec(_dateStr);

         var _dateList = [];

         if(_SplitSymbol == ""){

                   if(!(_dateStr.indexOf("") > _dateStr.indexOf("") && _dateStr.indexOf("") > _dateStr.indexOf("") && _dateStr.indexOf("")> 1))return new Date("x");

                   _dateList = _dateStr.split(/[年月日]/);

         }else _dateList = _dateStr.split(_SplitSymbol);

         if(_dateList.length < 2)return new Date("x");

         var _timeList = [1,1,1];

         if(_timeSplitSymbol.test(_timeStr)){

                   _SplitSymbol = _timeSplitSymbol.exec(_timeStr);

                   if(_SplitSymbol == ""){

                            if(!(_timeStr.indexOf("") > _timeStr.indexOf("") && _timeStr.indexOf("") > _timeStr.indexOf("") && _timeStr.indexOf("")> 1))return new Date("x");

                            _timeList = _timeStr.split(/[时分秒]/);

                   }else _timeList = _timeStr.split(_SplitSymbol);

         }

         return new Date(_dateList[0],_dateList[1],_dateList[2],_timeList[0],_timeList[1],_timeList[2]);

};

String.prototype.toNumber = function(){return new Number(this)};

Date.prototype.getQuarter = function(){return ((this.getMonth()+1)/3).ceil();};

Date.prototype.dateAdd = function(_timeInterval,_number){

         switch(_timeInterval.toUpperCase()){

                   case "YYYY":

                            return new Date(this.getFullYear() + _number,this.getMonth(),this.getDate(),this.getHours(),this.getMinutes(),this.getSeconds());

                            break;

                   case "MM":

                            return new Date(this.getFullYear(),this.getMonth() + _number,this.getDate(),this.getHours(),this.getMinutes(),this.getSeconds());

                            break;

                   case "DD":

                            return new Date(this.getFullYear(),this.getMonth(),this.getDate() + _number,this.getHours(),this.getMinutes(),this.getSeconds());

                            break;

                   case "H":

                            return new Date(this.getFullYear(),this.getMonth(),this.getDate(),this.getHours() + _number,this.getMinutes(),this.getSeconds());

                            break;

                   case "M":

                            return new Date(this.getFullYear(),this.getMonth(),this.getDate(),this.getHours(),this.getMinutes() + _number,this.getSeconds());

                            break;

                   case "S":

                            return new Date(this.getFullYear(),this.getMonth(),this.getDate(),this.getHours(),this.getMinutes(),this.getSeconds() + _number);

                            break;

                   case "WW":

                            return new Date(this.getFullYear(),this.getMonth(),this.getDate() + _number*7,this.getHours(),this.getMinutes(),this.getSeconds());

                            break;

                   default:return this;

         }

};

Date.prototype.formatDateTime = function(_nameFormate){

         switch(_nameFormate){

                   case 0:

                            return this.getFullYear().toString().right(2) + "/" + (this.getMonth() + 1).toString() + "/" + this.getDate().toString() + " " + this.getHours().toString() + ":" + this.getMinutes().toString() + ":" + this.getSeconds().toString();

                            break;

                   case 1:

                            return this.getFullYear().toString() + "" + (this.getMonth() + 1).toString() + "" + this.getDate().toString() + "";

                            break;

                   case 2:

                            return this.getFullYear().toString().right(2) + "/" + (this.getMonth() + 1).toString() + "/" + this.getDate().toString();

                            break;

                   case 3:

                            return this.getHours().toString() + ":" + this.getMinutes().toString() + ":" + this.getSeconds().toString();

                            break;

                   case 4:

                            return this.getHours().toString() + ":" + this.getMinutes().toString();

                            break;

                   default:

                            return this.getFullYear().toString().right(2) + "/" + (this.getMonth() + 1).toString() + "/" + this.getDate().toString() + " " + this.getHours().toString() + ":" + this.getMinutes().toString() + ":" + this.getSeconds().toString();

         }

};

Date.prototype.isNaN = function(){return isNaN(this);};

Number.prototype.abs = function(){return Math.abs(this)};

Number.prototype.acos = function(){return Math.acos(this)};

Number.prototype.asin = function(){return Math.asin(this)};

Number.prototype.atan = function(){return Math.atan(this)};

Number.prototype.atan2 = function(){return Math.atan2(this)};

Number.prototype.ceil = function(){return Math.ceil(this)};

Number.prototype.cos = function(){return Math.cos(this)};

Number.prototype.exp = function(){return Math.exp(this)};

Number.prototype.floor = function(){return Math.floor(this)};

Number.prototype.log = function(){return Math.log(this)};

Number.prototype.round = function(){return Math.round(this)};

Number.prototype.sin = function(){return Math.sin(this)};

Number.prototype.sqrt = function(){return Math.sqrt(this)};

Number.prototype.isNaN = function(){return isNaN(this)};

Number.prototype.tan = function(){return Math.tan(this)};

if(window){

         Array.prototype.alert = function(){window.alert(this);}

         Array.prototype.confirm = function(){return window.confirm(this);}

         String.prototype.alert = function(){window.alert(this)};

         String.prototype.confirm = function(){return window.confirm(this)};

         Date.prototype.alert = function(){window.alert(this.toLocaleDateString());};

         Date.prototype.confirm = function(){return window.confirm(this.toLocaleDateString());};

         Number.prototype.alert = function(){window.alert(this)};

         Number.prototype.confirm = function(){return window.confirm(this)};

         Boolean.prototype.alert = function(){window.alert(this);};

         Boolean.prototype.confirm = function(){return window.confirm(this);};

}

-----------------------------------------------------------------------------------------------------------------------

二、关于prototype属性

JavaScript1.1中,几个基本对象StringRegExpArrayDateNumberBooleanFunction增加了一个原型(prototype)属性,该属性容许程序员向已有对象原型添加新的属性和函数。其用法如下:

function obj(){

         this.id = “”;

}

obj.prototype.set_id = function(_value){

         this.id = _value;

}

var obj1 = new obj();

obj1.set_id(“test”);

通过prototype属性给obj类(事实上不是类,而是一个函数,这里只是为了方便表述)创建了一个函数(给set_id赋值为一个函数)。

prototype对于自定义的伪类意义不是很大,因为自定义的伪类也完全可以在构造函数中创建。

但是它对于已有的JavaScript对象类型的函数扩充有着比较重要的意义,通过prototype,可以给JS基本对象扩充新的函数。例如在js中没有类似于vbs中的trim函数,倘若单独把trim函数以及其他有用的函数写成一个独立的函数库,又失去了js脚本的那种语言简洁的特点。最理想的情况是将它扩充到已有的对象原型中去。

看看一些有趣的例子:

(“ 1234 ”).trim().alert(); //弹出一个对话框提示为1234

if(text1.value.toDate().isNaN())alert(“date input error!”); //在一个文本框中输入时间,格式不正确提示错误!

扩充的函数中比较有实用的是String的函数,trimleftrightisXXX等函数在表单的验证当中是比较常用的。