每个JavaScript对象都和另外一个对象相关联, 并从另外一个对象继承属性,另外一个对象就是"原型",
用直接量建立的对象 都具备同一个原型对象 Object.prototype 。
如下经过几个例子帮助咱们理解稍微理解原型---对象的属性一部分继承于该对象的原型。数组
/** * 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("-------------------");
/** * 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("------------------------");
/** * 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() );