Home > other >  Manipulating index of an array in javascript
Manipulating index of an array in javascript

Time:07-06

Is it possible to start the index at 1 instead of 0? For example, var cars = ["toyota","mazda","suzuki"]

and I use console.log(cars[1]), my expected output should be toyota. Here is my attempt to do this, but it returns undefined when I press 0.

document.addEventListener('keydown', function(event){
        
      const dataClasses = ["toyota", "mazda", "suzuki"];
      const eventKey = event.key-1;
      const arrayLength = dataClasses.length;
      console.log(event.key);

        if(!isNaN(eventKey)){
        if(eventKey < arrayLength) {
             const label = dataClasses[eventKey];
        console.log(label) 
        }    
      }
      
    });

CodePudding user response:

if(!isNaN(eventKey) && eventKey > -1){
 if(eventKey < arrayLength) {
  const label = dataClasses[eventKey];
  console.log(label) 
 }    
}

Just add this one more simple check to avoid 'undefined' getting printed when you press 0.

CodePudding user response:

The idea behind this answer is to explain that indexes to access the array should be separate from user input but each can be transformed into the other by adding or subtracting 1.

This is not recommended at all, but you can do const dataClasses = [undefined, "toyota", "mazda", "suzuki"]; this way dataClasses[1] is 'toyota'.

What you should actually be doing is const dataClasses = ["toyota", "mazda", "suzuki"]; and just tansforming the user's input (1,2,3) to indexes (0,1,2) by just subtracting 1.

  • Related