首页 > 代码库 > Array原生方法
Array原生方法
push()末尾推入元素 返回数组长度
pop()末尾弹出元素 返回弹出元素
shift()起始弹出元素 返回弹出元素
unshift()起始推入元素 返回数组长度
代码如:
var arr1 = ["b","c","d","e"];
var arr2 = arr1.push("f");//arr1:["b","c","d","e","f"], arr2:5
var arr3 = arr1.pop();//arr1:["b","c","d","e"], arr3:"f"
var arr4 = arr1.unshift("a");//arr1:["a","b","c","d","e"], arr4:5
var arr5 = arr1.shift();//arr1:["b","c","d","e"], arr5:"a"
Ecmascript5有扩展数组原型方法forEach,filter等
if(typeof Array.prototype.forEach !== "function"){
Array.prototype.forEach = function(fn,thisObj){
var scope = thisObj || window;
for(var i=0, len=this.length; i<len; i++){
fn.call(scope,this[i],[i],this);
}
}
};
if(typeof Array.prototype.filter!== "function"){
Array.prototype.filter= function(fn,thisObj){
var scope = thisObj || window;
var a = [];
for(var i=0, len=this.length; i<len; i++){
if(!fn.call(scope,this[i],[i],this)){
continue;
}
a.push(this[i])
}
return a;
}
}