您的位置:首页 > Web前端 > JavaScript

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

2012-10-22 21:20 441 查看
--------------------------内置对象

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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: