笔记:js内置对象及自定义对象

来源:互联网 发布:js 字符串转对象 编辑:程序博客网 时间:2024/05/16 23:02



--------------------------内置对象
String
Math
Date
Array
Event

 

------------String
str.length;
str.charAt(5);
str.indexOf(""); //找不到返回-1
str.toLowerCase();
str.toUpperCase();
str.subString(3,6);
str.replace("","");

 

-------------math
Math.PI
Math.LN2
Math.LOG2E
Math.SQRT2
Math.max(..,..);
Math.min(..,..);
Math.round(...); //对参数四舍五入
Math.floor(..);  //取不大于参数的整数
Math.ceil(..);  //取不小于参数的整数
Math.random();  //生成0-1的随机数

 

--------------Date
Date对象三种方法
1.从系统中获取当前的时间和日期

<script language="javascript">var now=new Date();document.write(now.getYear()+ "年" + (now.getMonth() + 1) + "月" + now.getDate()+ "日" + now.getHours()+ ":" + now.getMinutes() + ":" + now.getSeconds());</script>


月用0-11表示,因此应加1

 

2.设置当前时间和日期

<script language="javascript">var now=new Date();now.setMonth(10);now.setDate(23);document.write(now.getYear() + "--" + (now.getMonth() + 1) + "--" + now.getDate());</script>


3.时间,日期转换成其他格式

<script language="javascript">var now=new Date();now.setMonth(10);now.setDate(23);document.write(now.getYear() + "--" + (now.getMonth() + 1) + "--" + now.getDate() + "<br>");document.write(now.toGMTString() + "<br>");//返回GMT格式时间document.write(now.toLocaleString() + "<br>");//返回本地时间</script>

 

结果显示:
2012--11--23
Fri, 23 Nov 2012 12:47:22 UTC
2012年11月23日星期五 20:47:22

 

-------------Array

<script language="javascript">var a= new Array(3);a[0]=1;a[1]=4;a[2]=2;for(i=0; i<3; i++) {document.write("a[" + i + "]:" + a[i] + "<br />");}document.write("<br>");a.sort();//以ascii代码来排列先后顺序for(i=0; i<3; i++) {document.write("a[" + i + "]:" + a[i] + "<br />");}document.write("<br>");a.reverse();//数组内元素倒置for(i=0; i<3; i++) {document.write("a[" + i + "]:" + a[i] + "<br />");}document.write("<br>" + a.join());//数组内元素弄成字符串插入页面</script>


 

-----------------自定义对象

<script language="javascript">function printColor() {document.write("color is:" + this.color + "<br>");}function printSize() {document.write("size is:" + this.size + "<br>");}function app(tcolor, tsize) {this.color=tcolor;this.size=tsize;this.pcolor=printColor;//定义对象的pcolor方法this.psize=printSize;}var app1 = new app("green", 10);var app2 = new app("magenta", 20);app1.pcolor();app1.psize();app2.pcolor();app2.psize();</script>


 

原创粉丝点击