在JavaScript中存储key =>值数组的最佳方法? [英] Best way to store a key=>value array in JavaScript?

查看:137
本文介绍了在JavaScript中存储key =>值数组的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在javascript中存储 key =>值数组的最佳方法是什么?如何循环使用?



每个元素的键应该是一个标记,例如 {id} 或只是 id 和值应该是id的数值。



它应该是现有javascript类的元素,或者是一个可以通过可以使用jQuery。

解决方案

这就是什么一个JavaScript对象是:

  var myArray = {id1:100,id2:200,tag with spaces:300}; 
myArray.id3 = 400;
myArray [id4] = 500;

您可以使用 for..in loop :<对于(myArray中的var键){
console.log(key+ key +has value+ myArray的[键]);
}

另请参阅:使用对象(MDN)。



在ECMAScript6中还有 Map (参见那里的浏览器兼容性表):



  • 一个对象有原型,因此地图中有默认键。这可以通过使用自ES5以来的map = Object.create(null)来绕过,但很少完成。


  • 对象的键是字符串和符号,它们可以是地图的任何值。


  • 当您必须手动跟踪对象的大小时,您可以轻松获得地图的大小。




What's the best way to store a key=>value array in javascript, and how can that be looped through?

The key of each element should be a tag, such as {id} or just id and the value should be the numerical value of the id.

It should either be the element of an existing javascript class, or be a global variable which could easily be referenced through the class.

jQuery can be used.

解决方案

That's just what a JavaScript object is:

var myArray = {id1: 100, id2: 200, "tag with spaces": 300};
myArray.id3 = 400;
myArray["id4"] = 500;

You can loop through it using for..in loop:

for (var key in myArray) {
  console.log("key " + key + " has value " + myArray[key]);
}

See also: Working with objects (MDN).

In ECMAScript6 there is also Map (see the browser compatibility table there):

  • An Object has a prototype, so there are default keys in the map. This could be bypassed by using map = Object.create(null) since ES5, but was seldomly done.

  • The keys of an Object are Strings and Symbols, where they can be any value for a Map.

  • You can get the size of a Map easily while you have to manually keep track of size for an Object.

这篇关于在JavaScript中存储key =&gt;值数组的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆