【问题标题】:How to 'cycle' through the indexes of an associative array in Javascript如何在Javascript中通过关联数组的索引“循环”
【发布时间】:2016-01-31 08:41:27
【问题描述】:

这是一个 toggle 有 2 个或更多项目,需要选择下一个项目,以便依次选择所有值。

这个特定关联数组中的索引是唯一的,它们的数量是可变的(2 个或更多),并且没有原型元素。我知道旧索引,我想将新索引设置为找到的下一个索引(如果旧索引恰好是最后一个,则设置为第一个)。

这是我想出的,但我想知道是否有更优雅的方式。关联数组为strings,旧索引为oldx

var i, 
    seen_oldx = 0, 
    newx = "";

for (i in strings) {
  if (seen_oldx) {
    newx = i; // index after oldx (not reached if oldx is last)
    break; // found it, stop looking
  }
  else if (i === oldx) 
    seen_oldx = 1;
  else if (!newx) 
    newx = i; // newx is the first (in case oldx is last)
  }
}

【问题讨论】:

  • 'new' 是 JavaScript 中的保留字,不能作为变量使用。
  • 请添加strings的内容。
  • 例如(但其实没关系,可以改变,只要至少有2个条目即可;内容可以是任意对象):strings = {'a':' A','b':'B','c':'C'}
  • 请添加一些示例,而对象属性没有顺序应该如何获取“下一个”项目。
  • 解决方案是我的代码假设当对象没有改变时,for-in 枚举索引的顺序不会改变。我相当肯定它是可以信赖的,但从规格的角度来看,当然不能保证。一个更长更麻烦的解决方案可能会采用所有索引的一次性数组,然后循环遍历该数组,以它们的数量为模递增索引。这可能更清晰。

标签: javascript associative-array


【解决方案1】:

如果不添加另一个小数据结构,似乎没有一个真正优雅的解决方案。我最终添加了字符串关联数组的所有索引的适当数组:

for (var i in strings) i_strings.push(i);

然后代码就是:

newx = (oldx + 1) % i_strings.length;

【讨论】:

    【解决方案2】:

    您似乎在描述一个堆栈。因此,您只需根据需要将项目从堆栈中弹出,不需要索引等。

    这是 LIFO - 后进先出

     var stack=[];
     stack.push(1);
     stack.push(2);
     stack.push(3);
    

    然后删除项目

     var result = stack.pop();
    

    【讨论】:

    • 我想到的更多的是一个循环列表。但问题是如何在代码中优雅地将其链接到我的关联数组。
    【解决方案3】:

    这是一个提案,其中包含一个数据数组和一个数组属性array.index 用于保留最后一个索引和一个用于返回数组下一个元素的函数。

    var array = ['yellow', 'green', 'blue', 'orange'],
        i;
    
    function getNext(array) {
        if (!('index' in array)) {                // test if property index exist
            array.index = -1;                     // if not create one with start value -1
        }
        array.index++;                            // increment index
        array.index = array.index % array.length; // move the index into the right interval
        return array[array.index];                // return element
    }
    
    for (i = 0; i < 10; i++) {
        document.write(getNext(array) + '<br>');
    }

    【讨论】:

    • 确实,我最终添加了一个包含字符串关联数组的所有索引的适当数组:var i, j = 0; for (i in strings) i_strings[j++] = i;然后代码就是:newx = (oldx + 1) % i_strings.length;
    • 我不知道你可以用非正整数索引元素“重载”一个普通数组,这在一段时间内会派上用场..!我想这就是所有非原始对象在 javascript 中的工作方式,它们可以有一个或两个。
    • “普通”数组只是一个具有一些特殊功能的对象。
    猜你喜欢
    • 1970-01-01
    • 2017-07-10
    • 2014-06-11
    • 2011-01-23
    • 1970-01-01
    • 1970-01-01
    • 2020-03-31
    • 1970-01-01
    • 2014-07-15
    相关资源
    最近更新 更多