Array数组

varmyArray=newArray();//创建一个空数组

varmyArray=newArray(5);//创建一个大小为5数组,此时如果直接引用myArray[0],会返回undefined。

varmyArray=new(0,1,2,3);//创建一个初始值为0123的数组

varmyArray=[0,1,2,3];//创建一个初始值为0123数组

数组只要创建了,其长度是可以改变的,比如,创建了长度为5的数组,可以对其下标为5、6等赋值,这时长度会自动跟着改变。

但如果只是声明varmyArray;则不能引用数组中的任何元素,否则出错。

这里要注意newArray(5)和newArray("5")的区别,前者代表创建一个大小为5的数组,后者代表创建大小为1,初始值为字符串5的数组。

JavaScript中的数组可以存放不同类型的数据,比如一个数组可以同时存整数和字符串等。

数组的属性有:

constructor:引用数组的构造函数

length:返回数组元素的个数,如果在创建数组时指定了数组的大小,则无论数组是否赋值,都返回这个大小。

prototype:用于定义数组时添加新的属性和方法。

数组的方法有:

concat(合并数组),pop(),删除数组的最后一个元素,长度自动减1,reverse,push,shift等。

Object对象

它是一切对象的父对象,所有的对象都继承于它,因此它拥有的属性和方法,其他对象都有。

Object的属性:

constructor:引用数组的构造函数

prototype:添加新的属性和方法。

Object的方法有:

valueOf():返回对象的原始值

toString():用于将一个函数转换为字符串下面是object对象的示例:

<HTML>
<HEAD>
<TITLE>使用Object的示例</TITLE>
<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">

var obj1=new Object(false);

document.write("obj1=new Object(false)"+"<BR>");
document.write("obj1.constructor="+obj1.constructor+"<BR>");
document.write("obj1.valueOf()="+obj1.valueOf()+"<BR>");
document.write("obj1.toString()="+obj1.toString()+"<BR>");

var obj2=new Object("Hello World!");
document.write("obj2=new Object('Hello World!')"+"<BR>");
document.write("obj2.constructor="+obj2.constructor+"<BR>");
document.write("obj2.valueOf()="+obj2.valueOf()+"<BR>");
document.write("obj2.toString()="+obj2.toString()+"<BR>");

</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>

执行结果:

obj1=newObject(false)

obj1.constructor=functionBoolean(){[nativecode]}

obj1.valueOf()=false

obj1.toString()=false

obj2=newObject('HelloWorld!')

obj2.constructor=functionString(){[nativecode]}

obj2.valueOf()=HelloWorld!

obj2.toString()=HelloWorld!

window对象

是当前浏览器窗口对象,包含了document,navigator,location,history等子对象。

window对象的属性:

closed,document,frames,history,length(当前窗口的框架的数量),location,name,opener,

status(状态栏),self(当前窗口),top(最上面一层窗口)。

包括的方法也很多,如alert,confirm,blur等

navigator对象

用于获取当前浏览器的各种信息,主要用于判断客户端使用什么浏览器。示例如下;

<HTML>
<HEAD>
  <TITLE>navigator示例</TITLE>
<HEAD>
<BODY>
<script language="javascript">
document.write("浏览器代码名称:"+navigator.appCodeName+"<BR>");
document.write("浏览器名称:"+navigator.appName+"<BR>");
document.write("浏览器版本号:"+navigator.appVersion+"<BR>");
document.write("是否支持java:"+navigator.javaEnabled()+"<BR>");
document.write("MIME类型数:"+navigator.mimeTypes.length+"<BR>");

document.write("操作系统平台:"+navigator.platform+"<BR>");
document.write("插件数:"+navigator.plugins.length+"<BR>");
document.write("用户代理:"+navigator.userAgent+"<BR>");
</script>
</BODY>

</HTML>

在IE浏览器中执行结果:

浏览器代码名称:Mozilla

浏览器名称:MicrosoftInternetExplorer

浏览器版本号:4.0(compatible;MSIE8.0;WindowsNT5.1;Trident/4.0;.NETCLR2.0.50727;

.NETCLR3.0.4506.2152;.NETCLR3.5.30729;.NETCLR1.1.4322;InfoPath.2)

是否支持java:true

MIME类型数:0

操作系统平台:Win32

插件数:0

用户代理:Mozilla/4.0(compatible;MSIE8.0;WindowsNT5.1;Trident/4.0;.NETCLR2.0.50727;

.NETCLR3.0.4506.2152;.NETCLR3.5.30729;.NETCLR1.1.4322;InfoPath.2)

此外还有location对象,history对象,screen对象