Javascript - 将所有数组值的索引存储在变量中

时间:2011-04-18 09:37:21

标签: javascript arrays dynamic-variables

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

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

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数组,并生成一个新变量来存储索引。

2 个答案:

答案 0 :(得分:0)

似乎确保您的索引价值合法将是困难的。我将包含jquery并使用inArray方法返回数组中项的索引。

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
}

答案 1 :(得分:0)

The simplest solution is simply to build an Object which gives you nearly O(1) lookup time, and will scale with your array:

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

Now you can simply "lookup" your index from the FruitLookup table when needed like:

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

Now if you modify your array you simply need to run LinkFruits(fruits).

Technical Note: If you want to fully automate this process you can look into Array.observe() which is now deprecated. Or overload the push and pop methods of this array to trigger the update before falling back to the default prototype methods.