如何在javascript中定义一组键/值以及查找值并按顺序迭代该集?

如何在javascript中定义一组键/值以及查找值并按顺序迭代该集?,javascript,Javascript,我有一组键/值,例如橙色=123,香蕉=4,苹果=567。如何将这些键/值存储在javascript对象中,以便: 通过查找检索值,例如set[“orange”]应返回123和 按照添加键/值对的顺序迭代集合 看来是1。对象文字是合适的,但迭代顺序不能保证,对于2。键/值对(对象文字)数组将提供迭代顺序,但不能基于键查找值 @*谢谢所有的答案-这个问题不是常见的吗?像jQuery这样的库不支持这种类型吗?您的两个假设都是正确的。对象文字不保证以任何顺序返回键 在不旋转自己类型的情况下执行此操作的

我有一组键/值,例如橙色=123,香蕉=4,苹果=567。如何将这些键/值存储在javascript对象中,以便:

  • 通过查找检索值,例如set[“orange”]应返回123和
  • 按照添加键/值对的顺序迭代集合
  • 看来是1。对象文字是合适的,但迭代顺序不能保证,对于2。键/值对(对象文字)数组将提供迭代顺序,但不能基于键查找值


    @*谢谢所有的答案-这个问题不是常见的吗?像jQuery这样的库不支持这种类型吗?

    您的两个假设都是正确的。对象文字不保证以任何顺序返回键

    在不旋转自己类型的情况下执行此操作的唯一方法是维护有序的键列表:

    var obj = {
        orange:123,
        banana:4,
        apple:567
    }
    
    var keys = ['orange', 'banana', 'apple'];
    
    for (var i=0; i<keys.length; i++){
      value = obj[keys[i]]];
    }
    
    var obj={
    橙色:123,
    香蕉:4,
    苹果:567
    }
    var key=['橙色','香蕉','苹果'];
    
    对于(var i=0;i您可以用不同的方式进行:

    var a = {'orange':123, 'banana':4, 'apple':567};
    
    var b = new Object();
    b['orange'] = 123;
    b['banana'] = 4;
    b['apple'] = 567;
    
    var c = new Object();
    c.orange = 123;
    c.banana = 4;
    c.apple = 567;
    

    语法不同,但三个声明在内部是等效的。

    制作自己的列表构造函数怎么样

    function List(obj) {
    
      if (this instanceof List) {
       var t     = this,
           keys  = [];
    
        /* inititalize: add the properties of [obj] to the list, 
           and store the keys of [obj] in the private keys array */
        for (var l in obj) {
           keys.push(l);
           t[l] = obj[l];
        }
        /* public:
           add a property to the list 
        */
         t.add = 
             function(key, value) {
                  t[key] = value;
                  keys.push(key);
                  return t; /* allows method chaining */
                };
    
        /* public:
           return raw or sorted list as string, separated by [separator] 
           Without [sort] the order of properties is the order in which 
           the properties are added to the list
        */
         t.iterate =
           function(sort,separator){
             separator = separator || '\n';
             var ret   = [],
                 lkeys = sort ? keys.slice().sort() : keys;
    
             for (var i=0;i<lkeys.length;i++){
               ret.push(lkeys[i]+': '+t[lkeys[i]]);
             }
           return ret.join(separator);
          };
    
      } else if (obj && obj instanceof Object) {
         return new List(obj);
    
      } else if (arguments.length === 2) { 
         var a    = {};
         a[String(arguments[0])] = arguments[1];
         return new List(a);
    
      } else { return true; }
    
     /* the 'if (this instanceof List)' pattern makes
        the use of the 'new' operator obsolete. The 
        constructor also allows to be initialized with
        2 parameters => 'List(key,value)' 
     */
    }
    

    一个简单的封装:

    function Dictionary(p)
    {
        if(!this.Add)
        {
            Dictionary.prototype.Add = function(a)
            {
                if(!a.length) {a = [a];}
                for(var i = 0, n=a.length; i<n; i++)
                {
                    for(x in a[i])
                    {
                        this[x] = a[i][x];
                        this.keys.push(x);
                    }
                }
            }
        }
    
        this.keys = [];
    
        if(typeof(p)!='undefined') {this.Add(p);}
    }
    
    var a = new Dictionary({'orange':123, 'banana':4, 'apple':567});
    
    alert(a.keys);//returns [orange,banana,apple]
    
    alert(a.keys[0]);//returns orange
    
    alert(a.orange) //returns 123
    
    a.Add({'mango':88}); //another way to add data
    
    a.Add([{kiwi:16},{grapefruit:79}]) //another way to add data
    
    alert(a.keys);//returns [orange,banana,apple,mango,kiwi,grapefruit]
    
    函数字典(p)
    {
    如果(!this.Add)
    {
    Dictionary.prototype.Add=函数(a)
    {
    如果(!a.length){a=[a];}
    
    对于(var i=0,n=a.length;iSame question,想要一些响应我认为您无法以任何可预测的顺序迭代对象,因此这将失败问题的条件2。不过,将所有这些封装在他自己的类型中会更好…或者只使用数组实现键值对:var data=[[“orange”,123],“banana”,4],“apple”,567]];如果你将其格式化并简化为可读的形式,我会被说服更新投票。你希望它的格式是什么?我很乐意编辑它更多的原型,更多的注释,更多的空白,更少的代码。但我现在无论如何都会更新投票给你-我已经发布了我自己的实现。好吧,我会添加一些注释。更多的原型,为什么t?我可以用一个版本来替换这个构造函数,并将其添加到对象原型中。谢谢你的投票。你以后可以做一些事情,但如果你在这里发布代码,而有人复制了它,你不能保证他们会知道这样做。你有责任发布尽可能最好的代码。而且原型设计更干净:)
    function Dictionary(p)
    {
        if(!this.Add)
        {
            Dictionary.prototype.Add = function(a)
            {
                if(!a.length) {a = [a];}
                for(var i = 0, n=a.length; i<n; i++)
                {
                    for(x in a[i])
                    {
                        this[x] = a[i][x];
                        this.keys.push(x);
                    }
                }
            }
        }
    
        this.keys = [];
    
        if(typeof(p)!='undefined') {this.Add(p);}
    }
    
    var a = new Dictionary({'orange':123, 'banana':4, 'apple':567});
    
    alert(a.keys);//returns [orange,banana,apple]
    
    alert(a.keys[0]);//returns orange
    
    alert(a.orange) //returns 123
    
    a.Add({'mango':88}); //another way to add data
    
    a.Add([{kiwi:16},{grapefruit:79}]) //another way to add data
    
    alert(a.keys);//returns [orange,banana,apple,mango,kiwi,grapefruit]