0

假设我在 JS 中有一个数组: var fruits = [apple,orange,banana] 我想将每个水果的索引存储在变量中,这样在任何时候,如果我在数组中添加更多的东西,我仍然会知道苹果的索引是 X。所以在这种情况下,0 是苹果,但是如果我在开头添加一些东西,苹果的索引就会改变。

我能想到的更详细的方法是遍历数组

for (var i=0;i<fruits.length;i++) {
   switch(fruits[i]) {
    case:"apple"
      var indexApple = i;
      break;
    //etc 
   }
}

我能想到的另一种方法是使用数组的值作为变量名。

for (var i=0;i<fruits.length;i++) {
  //psedo code
  var 'index' + fruits[i] = i;
}

所以最后我会有 var indexApple = 0, indexOrange = 1 等。第二种方法的关键是能够通过连接字符串'index'和数组的值来创建一个动态变量来创建它多变的。不知道该怎么做。

注意:理想情况下,我希望动态生成存储索引的变量。这样我只有我可以修改/添加到 fruits 数组,并且将生成一个新变量来存储索引。

4

2 回答 2

0

it seems like ensuring your the value of the index is legitimate will be difficult. i would include jquery and use the inArray method which returns the index of the item in the array.

function showIndexes() {
  var appleIndex = $.inArray(fruits, "Apple"); //returns 0
  var guavaIndex = $.inArray(fruits, "Guava"); //returns -1

  fruits.unshift("Guava");
  appleIndex = $.inArray(fruits, "Apple"); //returns 1
  guavaIndex = $.inArray(fruits, "Guava"); //returns 0
}
于 2011-04-18T09:54:22.730 回答
0

最简单的解决方案是简单地构建一个 Object ,它可以为您提供几乎 O(1) 的查找时间,并且会随着您的数组扩展:

function LinkFruits(fruits) {
    FruitLookup = {}
    fruits.forEach((fruit,ind) => FruitLookup[fruit] = ind)
}

现在,您可以在需要时简单地从表中“查找”您的索引,FruitLookup例如:

console.log("The index of apple is",FruitLookup.apple,"and for orange is",FruitLookup.orange)

现在,如果您修改您的阵列,您只需要运行LinkFruits(fruits).

技术说明:如果您想完全自动化此过程,您可以查看Array.observe()现在已弃用的。或者重载这个数组的pushandpop方法来触发更新,然后再回退到默认的原型方法。

于 2016-02-12T19:23:49.690 回答