首页
极刻
圈子
教程
开源
登录 / 注册
返回教程:Javascript 教程
TRY RUN / 在线示例
Javascript 教程 尝试一下
Javascript 教程 尝试一下
源代码
运行
<!DOCTYE 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('0000');"/> </body> </html>
运行结果