ITeye博客

关于javascript的Array对象

qsrock · 2009-07-09 08:23 · javascript · Markdown

//Javascript中Array的默认方法里没有提供indexOf方法(在IE不提供,在firefox上有的),那也自己动手加一个进去 
//以prototype方式来Hack Javascript 真的很爽

if (!Array.prototype.indexOf) {
	Array.prototype.indexOf = function(item, i) {
		i || (i = 0);
		var length = this.length;
		if (i < 0) i = length + i;
		for (; i < length; i++)
		if (this[i] === item) return i;
		return -1;
	};
}

利用上面函数重写了下面的2个方法

function push(){//txt不存在才添加进来
	var txt = document.getElementById("pushText").value;
	if(rosterArray.indexOf(txt)==-1){
		rosterArray.push(txt);
	}
	
	alert(txt+"---------"+rosterArray.length+"---"+rosterArray);
}
function pop(){//txt存在才删除
	var txt = document.getElementById("popText").value;
	var position = rosterArray.indexOf(txt);
	if(position != -1){
		rosterArray.splice(position,1);
//删除,可参考http://stephen830.iteye.com/blog/340722
	}
	
	alert(txt+"---------"+rosterArray.length+"---"+rosterArray);
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。