Array类型的调整数组数量的几个方法
常见的有如下几个:
- push()方法
- pop()方法
- shift()方法
- unshift()方法
push()方法和pop()方法:
push()方法可接受不了任意数量的参数,把它们逐个添加到数组末尾,并返回修改后的参数;pop()方法会从数组的末尾删除掉最后一项,并返回被移除的值。
var colors=new Array();var count=colors.push("red","green");alert(count); //2count=colors.push("black");alert(count); //3var item=colors.pop();alert(item);alert(colors.length);
上面一段代码会添加数组的最后一项,并移除最后一项,这段代码可以看成一个栈,值得注意的是,如果用其他的方法,使得数组中间有"空位"的话,中间的空位会被设置成undefined数据类型。如下:
var colors=["red","blue"]; colors[3]="black"; colors.push("brown"); alert(colors[2]);
代码第二行:当数组的第四位被设置成"black"的时候,第三位并没有值,而使用push()方法则会直接添加到最后一位(即第五位),而第三位则会是undefined。
shift()方法和unshift()方法:
shift()方法可移除数组中的第一个项,并返回该项;unshift()方法看起来向反,它能在数组前端添加任意个项,并返回数组新的长度。
var colors=new Array();var count=colors.unshift("red","green");alert(count); //2count=colors.unshift("black");alert(count); //3var item=colors.pop();alert(item); //greenalert(colors.length); //2