var myarray = new array(); //创建一个空数组
var myarray = new array(5); //创建一个大小为5数组,此时如果直接引用myarray[0],会返回undefined。
var myarray = new (0,1,2,3); //创建一个初始值为0123的数组
var myarray = [0,1,2,3]; //创建一个初始值为0123数组
数组只要创建了,其长度是可以改变的,比如,创建了长度为5的数组,可以对其下标为5、6等赋值,这时长度会自动跟着改变。
但如果只是声明var myarray;则不能引用数组中的任何元素,否则出错。
这里要注意new array(5)和new array(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=new object(false)
obj1.constructor= function boolean() { [native code] }
obj1.valueof()=false
obj1.tostring()=false
obj2=new object('hello world!')
obj2.constructor= function string() { [native code] }
obj2.valueof()=hello world!
obj2.tostring()=hello world!
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
浏览器名称:microsoft internet explorer
浏览器版本号:4.0 (compatible; msie 8.0; windows nt 5.1; trident/4.0; .net clr 2.0.50727;
.net clr 3.0.4506.2152; .net clr 3.5.30729; .net clr 1.1.4322; infopath.2)
是否支持java:true
mime类型数:0
操作系统平台:win32
插件数:0
用户代理:mozilla/4.0 (compatible; msie 8.0; windows nt 5.1; trident/4.0; .net clr 2.0.50727;
.net clr 3.0.4506.2152; .net clr 3.5.30729; .net clr 1.1.4322; infopath.2)
此外还有location对象,history对象,screen对象