日期:2014-05-16  浏览次数:20462 次

js数组的扩展方法

1、用于清空数组

Array.prototype.clear = function() {
    this.length = 0;
}

2、判断数据项在数组中的位置

varoldArrayIndexOf = Array.indexOf;//判断是否原始浏览器是否存在indexOf方法
Array.prototype.indexOf = function(obj) {
    if(!oldArrayIndexOf) {
        for(vari = 0, imax = this.length; i < imax; i++) {
            if(this[i] === obj) {
                returni;
            }
        }
        return-1;
    } else{
        returnoldArrayIndexOf(obj);
    }
}

3、判断数据项是否在该数组中

Array.prototype.contain = function(obj) {
    returnthis.indexOf(obj) !== -1;
}

4、把数据项添加到指定的位置

Array.prototype.insertAt = function(index, obj) {
    if(index < 0) index = 0;     if(index > this.length) index = this.length;
    this.length++;
    for(vari = this.length - 1; i > index; i--) {
        this[i] = this[i - 1];
    }
    this[index] = obj;
}

5、返回最有一项数据

Array.prototype.last = function() {
    returnthis[this.length - 1];
}

6、移除数组指定索引的值

Array.prototype.removeAt = function(index) {
    if(index < 0 || index >= this.length) return;
    varitem = this[index];
    for(vari = index, imax = this.length - 2; i < imax; i++) {         this[i] = this[i + 1];     }     this.length--;     returnitem; }

7、移除数据项的数据

Array.prototype.removeAt = function(obj) {     varindex = this.indexOf(obj);     if(index >= 0)