Array对象扩展

[size=large]虽然现在各大高级浏览器都支持了数组对象的扩展方法,例如some,forEach等,但是为了兼容各低端浏览器,流行框架会添加自己的支持方法,下面列出常用的一些扩展:[/size]

<script>
Array.prototype.indexOf = function(item, fromIdx){
var length = this.length;
fromIdx = fromIdx == null ? 0 : fromIdx < 0 ? Math.max(0, fromIdx + length) : fromIdx;
for(; fromIdx < length; fromIdx++){
if(fromIdx in this && this[fromIdx] === item){
return fromIdx;
}
}
return -1;
}

Array.prototype.lastIndexOf = function(item, fromIdx){
var length = this.length;
fromIdx = fromIdx == null ? length -1 : fromIdx < 0 ? Math.max(0, fromIdx + length) : fromIdx;
for(; fromIdx > -1; fromIdx--){
if(fromIdx in this && this[fromIdx] === item){
return fromIdx;
}
}
return -1;
}

Array.prototype.forEach = function(callback, thisObj){
thisObj = thisObj || window;
for(var i = 0, len = this.length; i < len; i++){
callback.call(thisObj, this[i], i, this);
}
}

Array.prototype.every = function(callback, thisObj){
thisObj = thisObj || window;
for(var i = 0, len = this.length; i < len; i++){
if(!callback.call(thisObj, this[i], i, this)){
return false;
}
}
return true;
}

Array.prototype.some = function(callback, thisObj){
thisObj = thisObj || window;
for(var i = 0,len = this.length; i < len; i++){
if(callback.call(thisObj, this[i], i , this)){
return true;
}
}
return false;
}

Array.prototype.filter = function(callback, thisObj){
var arr = [];
thisObj = thisObj || window;
for(var i = 0,len = this.length; i < len; i++){
if(callback.call(thisObj, this[i], i , this)){
arr.push(this[i]);
}
}
return arr;
}

Array.prototype.map = function(callback, thisObj){
thisObj = thisObj || window;
for(var i = 0, len = this.length; i < len; i++){
callback.call(thisObj, this[i], i, this);
}
}

Array.prototype.reduce = function(callback, initVal){
var i = 0, len = this.length;
if(!initVal){ //没有初始值则寻找arr里第一个值
for(;i < len; i++){
if(i in this){
initVal = this[i];break;
}
}
if(!initVal){
throw new Error('no reduce element');
}
}
for(; i < len; i++){
if(i in this)
initVal = callback.call(null, initVal, this[i], i, this);
}
return initVal;
}

Array.prototype.remove = function(obj){//逆序移除 避免splice的时候重置i
for(var i = this.length - 1; i >= 0; i--){
if(this[i] === obj){
this.splice(i, 1);
}
}
return this;
}

Array.prototype.unique = function(){
for(var i = this.length - 1; i >= 0; i--){
for(var j = i - 1; j >= 0; j--){
if(this[i] === this[j]){
this.splice(j, 1);
i--;
}
}
}
return this;
}

Array.prototype.unique2 = function(){
this.sort();
for(var i = this.length - 1; i > 0; i--){
if(this[i] === this[i - 1]){
this.splice(i, 1);
}
}
return this;
}
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值