Search code examples
javascriptarraysvariablesuser-input

How do I use a variable to find an element in an array?


I'd like to take some user input and use it to find a certain object in an array. But when I try to do it with the code below, I get an undefined error. What am I doing wrong?

function findNextLevel() {
    var currentLevel = parseFloat(document.getElementById("currentLevel").value);
    var xpForLevel = trainerLevels.currentLevel;
    document.getElementById("result01").innerHTML = xpForLevel;
}

Solution

  • I'm assuming that trainerLevels is an array and currentLevel is an index. If so, the way to access an element in an array at a certain index is to use brackets like so. Otherwise, could you provide more details in your question?

    var xpForLevel = trainerLevels[currentLevel];
    

    If this is the answer that you were looking for, then may I recommend that you use the parseInt rather than the parseFloat function for getting the index? And also, since it is user input, you may want to check that currentLevel is in the correct range as well.