简体   繁体   中英

Javascript - storing the index of all array values in a variable

Say I have an array in JS: var fruits = [apple,orange,banana] I want to store the index of each fruit in variables such that at any point in time, if I add more stuff to the array, I will still know that the index of apple is X. So in this case, 0 is apple, but if I add something to the beginning of that away, the index of apple changes.

The more verbose way I can think of is to loop through the array

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

Another way I can think of is use the value of the arrays as the variable name.

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

So in the end I'd have var indexApple = 0, indexOrange = 1, etc. THe key to the second method is to be able to create a dynamic variable by concatenating the string 'index' and the value of the array to create that variable. Not sure how to do that.

Note: Ideally I want the variables that store the index to be dynamically generated. Such that I only I can modify/add to the fruits array, and a new variable will be generated to store the index.

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM