本文将介绍JavaScript中的5个基本对象:
1. String对象
示例:
用法:substr(start,length)
<html>
<body>
<script>
var str="Happy new year!";
document.write(str.substr(6)+"<br/>");
document.write(str.substr(6,3)+"<br/>");
</script>
</body>
</html>
2. Date对象
使用示例:
(1)
<html>
<head>
<script src="clock.js"> </script>
</head>
<body οnlοad="showTime()">
<div id="nowDiv"></div>
</body>
</html>
clock.js:
function showTime(){
var date = new Date();
//分解date获取当前日期和时间并赋值给now
document.getElementById("nowDiv").innerHTML = now;
window.setTimeout("showTime()",1000);
//1000毫秒(1秒)调用一次showTime
}
(2)
<html>
<body>
<script>
var str=new Date();
document.write(str.toString()+"<br/>");
document.write(str.toLocaleString()+"<br/>");
document.write(str.toLocaleTimeString()+"<br/>");
document.write(str.toLocaleDateString()+"<br/>");
</script>
</body>
</html>
运行效果:
3.Math对象
示例:
<html>
<head>
<script>
function random(min,max){
return parseInt(min+Math.random()*(max-min+1));
//return Math.floor(min+Math.random()*(max-min+1));
}
</script>
</head>
<body>
<script>
for(i=0;i<100;i++) document.write( random(1,10) +" ");
</script>
</body>
</html>
4.Boolean对象
5.Array对象
示例:
在[mins,maxs]之间生成count个不同的随机正整数,用数组存放。
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script>
function creatArr(num, min, max)
{
var myArray = new Array(num);
for (i = 0; i < num; i++)
{
myArray[i] = parseInt(Math.random() * (max - min + 1));
}
}
creatArr(5, 1, 10);
for (j = 0; j < myArray.length; j++)
{
document.write(myArray[j]);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>