Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

javascript - 在JavaScript中存储key => value数组的最佳方法?(Best way to store a key=>value array in JavaScript?)

What's the best way to store a key=>value array in javascript, and how can that be looped through?(在javascript中存储key=>value数组的最佳方法是什么,以及如何循环?)

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.(每个元素的键应该是一个标记,例如{id}或只是id ,值应该是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.(它应该是现有javascript类的元素,或者是可以通过类轻松引用的全局变量。)

jQuery can be used.(可以使用jQuery。)

  ask by Click Upvote translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That's just what a JavaScript object is:(这就是JavaScript对象:)

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..in循环for..in它:)

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

See also: Working with objects (MDN).(另请参阅: 使用对象 (MDN)。)

In ECMAScript6 there is also Map (see the browser compatibility table there):(在ECMAScript6中还有Map (参见那里的浏览器兼容性表):)

  • An Object has a prototype, so there are default keys in the map.(Object有一个原型,因此地图中有默认键。)

    This could be bypassed by using map = Object.create(null) since ES5, but was seldomly done.(这可以通过使用自ES5以来的map = Object.create(null)来绕过,但很少完成。)
  • The keys of an Object are Strings and Symbols, where they can be any value for a Map.(Object的键是字符串和符号,它们可以是Map的任何值。)

  • You can get the size of a Map easily while you have to manually keep track of size for an Object.(您必须手动跟踪对象的大小,才能轻松获得Map的大小。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...