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

[JavaScript] 6.JS 常见内置对象

2016-05-16 19:02 465 查看

时间

使用以前必须先申明:
varcurr=new Date();
主要的方法
getyear,getmonth, …
setyear,setmonth, …
toLoacaleString();
<!DOCTYPE HTML PUBLIC "-//W3C//DTDHTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<metahttp-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>UntitledDocument</title>
<script>
functiontestDate() {

vardate2 = new Date();
// date2.setYear(1999);
// date2.setMonth(10-1);
// date2.setDate(10); //不设的话,就是以当前时间的日期算,其他的类似。
document.write(date2.getYear()+"年"+"<br>");
document.write(date2.getMonth()+1+"月"+"<br>");
document.write(date2.getDate()+"日"+"<br>");
document.write("星期"+date2.getDay()+"<br>");
document.write(date2.getHours()+"时"+"<br>");
document.write(date2.getMinutes()+"分"+"<br>");
document.write(date2.getSeconds()+"秒"+"<br>");
document.write("从1970.01.01至今"+date2.getTime()+"毫秒"+"<br>");
document.write(date2.toLocaleString()); //本地时间,即北京时间
document.write("<br>");
document.write(date2.toGMTString()); //格林尼治时间。

}

</script>
</head>
<body>
<ahref="javascript:void(0);" onclick="testDate();">测试date对象的方法</a>
</body>
</html>

Math

内置的Math对象可以用来处理各种数学运算
可以直接调用的方法:
Math.数学函数(参数)
求随机数方法
Math.random(),产生[0,1)范围的一个任意数
<!DOCTYPE HTML PUBLIC "-//W3C//DTDHTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<metahttp-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>UntitledDocument</title>
<script>
functiontestMath() {

varrandom1=Math.random();

varint1 = Math.round(random1*100); //产生0-100之间的任意一个整数。较常用

document.write(random1);
document.write("<br>");
document.write(int1);
}
</script>
</head>
<body>
<ahref="javascript:void(0);" onclick="testMath()">测试随机产生0-10之间的数值</a>
</body>
</html>

String

我们一般利用String对象提供的函数来处理字符串。String对字符串的处理主要提供了下列方法:
charAt(idx):返回指定位置处的字符   indexOf(Chr):返回指定子字符串的位置,从左到右。找不到返回-1
substr(m,n):返回给定字符串中从m位置开始,取n个字符,如果参数n省略,则意味着取到字符串末尾。
substring(m,n):返回给定字符串中从m位置开始,到n位置结束,如果参数n省略,则意味着取到字符串末尾。
toLowerCase():将字符串中的字符全部转化成小写。
toUpperCase():将字符串中的字符全部转化成大写。
length:属性,不是方法,返回字符串的长度。
<!DOCTYPE HTML PUBLIC "-//W3C//DTDHTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<metahttp-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>UntitledDocument</title>
<script>
functiontestString() {
varstr = "abcdefghigklmnopqrstuvwxyz";
// var str = newString("abcdefghigklmnopqrstuvwxyz");

document.write(str.charAt(2)+"<br>");

document.write(str.indexOf("f")+"<br>");

document.write(str.substring(3,5)+"<br>");//返回给定字符串中从m位置开始,到n位置结束,如果参数n省略,则意味着取到字符串末尾。

document.write(str.substr(3,5)+"<br>"); //返回给定字符串中从m位置开始,取n个字符,如果参数n省略,则意味着取到字符串末尾。

document.write(str.toUpperCase()+"<br>");;

//document.write(str.toLowerCase());
document.write(str.length);

}
</script>
</head>
<bodyonload="testString();">
</body>
</html>

业务思想

常见内置对象针对性、实用性都很强,作为编程人员很有必要进行一番理解。虽只是列举出常见内置对象,抛砖引玉,做以深度掌握,demo或项目中去实战才更会体会到其他用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: