Heim  >  Artikel  >  Web-Frontend  >  JavaScript 以对象为索引的关联数组_javascript技巧

JavaScript 以对象为索引的关联数组_javascript技巧

WBOY
WBOYOriginal
2016-05-16 18:26:45711Durchsuche

关于JSON对象,你可以参看wikipedia(http://zh.wikipedia.org/zh-cn/JSON),还有官方网站(http://www.json.org/json-zh.html)。

  我们常说JavaScript原生支持json,因为我们可以认为json就是对JavaScript的Object对象的灵活应用。

  通常我们使用json的方式,主要用作前后台数据交换的格式:

  而在代码逻辑中更多的是用关联数组的方式。但即使是这样我们也很少使用对象类型作为键值对的键名。
  var a= {}, b= [];
  a[b] = new Date(); //通过a[b]可以取得时间值。

  键名的类型可以是对象,多么美好的一件事啊!

  不过有一个问题。如果你想这么用,需要有一个条件:数据必须是动态添加的。(目前在同学这,没有条件测试其他的浏览器,目前测试了IE8以及搜狗浏览器的IE内核和weikit内核)

  测试代码如下:

复制代码 代码如下:

var d = document.getElementById("hello"), obj = [1,2,3], a = {obj:"test"};
a[d] = "DOMElement";
alert(a[obj]); //undefined
alert(a[d]);  //DOMElement
a[obj] = "Array Object";
alert(a[obj]);  //Array Object
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn