第5章引用类型

来源:互联网 发布:win8动态壁纸软件 编辑:程序博客网 时间:2024/06/08 13:11

第5章引用类型

5.1 Object类型

创建object实例方法

//使用new操作符var person1=new Object();person.name="张三";person.age=29;var person2={};person2.name="张三";person2.age=29;//使用对象字面表示法var person3={    name:"李四",    age:28};

使用的更多的是对象字面表示法,例子:

function displayInfo(args){    var output="";    if(typeof args.name == "string"){        output+="Name:" + args.name + "\n";    }    if(typeof args.age == "number"){        output+="Age:" + args.age + "\n";    }    alert(output);}displayInfo({    name:"bule",    age:18});displayInfo({    name:"red"})

5.2 Array类型

构造数组

var arr1=new Array();var arr2=new Array(20);var arr3=["red","green","yellow"];

5.2.1 检测数组

//方法一if (value instanceof Array){    //对数组执行某些操作}//方法二if(Array.isArray(value)){    //对数组执行某些操作}

5.2.3 栈方法

栈:后进先出
push()方法可以接受任意数量的参数,把它们逐个添加到数组末尾,并返回修改后数组的长度。而pop()方法则从数组末尾移除最后一项,减少数组的length值,然后返回移除的项。例子:

var colors=new Array();var count = colors.push("red","green");console.log(count);//2count = colors.push("black");console.log(count);//3console.log(colors);//"red","green","black"var item = colors.pop();console.log(item);//"black"console.log(colors);//"red","green"console.log(colors.length);//2

5.2.4 队列方法

队列:先进先出
shift()方法能够移除数组中的第一个项病并返回该项,同时将数组长度减一。结合使用push()。例子:

var colors=new Array();var count =colors.push("red","green");console.log(count);//2count = colors.push('black');console.log(count);//3var item = colors.shift();console.log(item);//redconsole.log(colors.length);//2

js还提供了一种