给数组原型添加方法

对象原型

每一个JavaScript对象都和另一个对象相关联, 并从另一个对象继承属性,另一个对象就是"原型",
用直接量创建的对象 都具有同一个原型对象 Object.prototype 。

以下通过几个例子帮助我们理解稍微理解原型---对象的属性一部分继承于该对象的原型。

1. 给数组原型添加把稀疏数组变为不稀疏数组的方法

/**
 * noSparse()
 * @return array resArr
 */
Array.prototype.noSparse = function(  ){
	var resArr = [];
	for( var i = 0 ; i < this.length ; i++ ){

		if( this[i] !== undefined ){
			resArr.push( this[i] );
		}
	}
	return resArr;
}

var arr_demo1 = [1,2,,,,,3,4,,'a',['A','B','C'],,'M'];
console.log( arr_demo1.noSparse(  ) );


console.log("-------------------");

2. 给数组原型添加检测一个元素在不在数组里面的方法

/**
 * inArray()
 * @params int type 当type === 1是 是全等比较  除此之外 都是比较值
 * @params fixed ele
 * @return boolean true or false
 * 
 */
Array.prototype.inArray = function(ele,type ){
	for( var i = 0 ; i < this.length ; i++ ){
		if( type === 1 ){
			if( ele === this[i] ){
				return true;	
			}
		} else {
			if( ele == this[i] ){
				return true;
			}
		}
		
	}

	return false;

}

var arr_demo2 = [1,3,5,7,9,'a','b'];
console.log( arr_demo2.inArray( "1",1) );



console.log("------------------------");

3. 给数组原型添加去重复元素方法

/**
 * noRepeat()
 * @return array resArr
 */
Array.prototype.noRepeat = function() {
	var resArr = [];
	for( var i = 0 ; i < this.length ; i++ ){
		if( !resArr.inArray( this[i] ,1 ) ){
			resArr.push( this[i] );
		}
	}

	return resArr;
}

var arr_demo3 = [1,1,2,2,4,5,3,5,6,7,5,3,8,9,8,9];
console.log( arr_demo3.noRepeat() );
原文地址:https://www.cnblogs.com/yi-0921/p/7404632.html