JavaScript学习实例-dictionary

下面实例来自W3CSchool 学习网站。

<!DOCTYPE html>
<html> 	
	<head> 	 	
		<script> 	 	
			function dictionary(){ 	 	
				//Define an object for a dictionary type 	 	
				var _obj = new Object(); 	 	
				//Check whether a certain key contained or not 	 	
				this.containsKey = function(k){ 	 	
					var isContained = false; 	 	
					for(var attr in _obj){ 	 	
						if(attr == k){ 	 	
							isContained = true; 	 	
							break; 	 	
						} 	 	
					} 	 	
					return isContained; 	 	
				} 	 	
				//Add a new element 	 	
				this.addElement = function(k,v){ 	 	
					if(!this.containsKey(k)){ 	 	
						_obj[k] = v; 	 	
					} 	 	
				} 	 	
				//Remove an existing element 	 	
				this.removeElement = function(k){ 	 	
					if(this.containsKey(k)){ 	 	
						delete _obj[k]; 	 	
					} 	 	
				} 	 	
				//Print the result 	 	
				this.printAll = function(){ 	 	
					var result = JSON.stringify(_obj); 	 	
					return result; 	 	
				} 	 	
			} 	 	
			var newD = new dictionary(); 	 	
			function AddAndPrint(){ 	 	
				newD.addElement("0000","张三"); 	 	
				newD.addElement("0001","李四"); 	 	
				document.getElementById("divContent").innerHTML = newD.printAll(); 	 	
			} 	 	
			function RemoveAndPrint(k){ 	 	
				newD.removeElement("0000"); 	 	
				document.getElementById("divContent").innerHTML = newD.printAll(); 	 	
			} 	 	
		</script> 	 	
	</head> 	 	
	<body> 	 	
		<div id="divContent"></div> 	 	
		<input type="button" value="Click Me To Add" onclick="AddAndPrint();"/> 	 	
		<input type="button" value="Click Me To Remove" onclick="RemoveAndPrint(&#39;0000&#39;);"/> 	 	
	</body> 	 	
</html>
发布了89 篇原创文章 · 获赞 83 · 访问量 3510

猜你喜欢

转载自blog.csdn.net/devin_xin/article/details/105255796