JavaScript API函數擴展,你自己有多少?

/**
 * 因爲長時間使用java,在js中一些數據類型和數據結構難免覺得不夠人性化,不夠方便,那怎麼辦呢?我們可以自己動手封裝一些常用了函數,
 * 因爲javascript把prototype(原型)留給我們了,呵呵,,好了廢話不多說,就來看看我常用的幾個函數:
 */

//js 關於數組操作的一些擴展方法:
//1.在數組中查找元素
	Array.prototype.indexOf = function (vItem) {
		  for (var i=0; i<this.length; i++) {
		    if (vItem == this[i]) {
			  return i;
			}
		  }
		  return -1;
}


//2.統計數組中某個元素出現的次數
	Array.prototype.count = function (vItem){
		var cunt = 0;
		for(var i=0;i<this.length;i++){
			if(vItem == this[i]){
				cunt ++;
			}
		}
		return cunt;
}

//3.刪除數組中某個下標的元素
	Array.prototype.removeElement  = function(index){
		if(index > 0 && this.length>index){
				for(var i = index;i<this.length;i++){
					this[index] = this[index+1]
				}
				this.length  = this.length -1;
		}
	}


//4.實現js中類似於java中的map數據結構
	Array.prototype.put = function(key,value){
		key  = key.toString();
		if(this[key] == null){
			this.push(key);
			this[key] = value;
			document.write("arr is:"+this);
		}
	}
	Array.prototype.get = function(key){
		return this[key.toString()];
	}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章