欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Array对象扩展

程序员文章站 2022-06-07 13:20:21
...
[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>
相关标签: foreach