您的位置:首页 > Web前端 > JavaScript

JavaScript中用数组实现键值对

2014-06-06 15:15 232 查看
转自:http://jsj.52zxw.net/article_view.php/99.html

vbs中有dictionary对象,js中也有相应的对象,可js的dictionary对象不是跨浏览器的,所以用数组实现了键值对的功能。

  今天写浏览器端js程序,需要用到键值对的功能,vbs中有dictionary对象,js中也应该有对应的dictionary对象,查了一下js手册,js中果然有dictionary对象,程序写好了,跨浏览器一测试,发现只有IE支持new ActiveXObject("Scripting.Dictionary"),其他浏览器或许有兼容写法,支持dictionary对象,网上搜索了一下,没有搜到,突然想到js的数组,查了一些资料,实现了我想要的功能,跨浏览器测试一下,谷歌、火狐、opera都兼容,以下是程序代码,参考了网上的一个例子,稍作了下修改:

<script type="text/javascript" language="javascript">

//自定义字典对象

function Dictionary(){

this.data = new Array();

this.put = function(key,value){

this.data[key] = value;

};

this.get = function(key){

return this.data[key];

};

this.remove = function(key){

this.data[key] = null;

};

this.isEmpty = function(){

return this.data.length == 0;

};

this.size = function(){

return this.data.length;

};

}

//使用 例子

var d = new Dictionary();

d.put("CN", "China");

d.put("US", "America");

document.write(d.get("CN"));

</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: