2

I'm attempting to create a lookup table in Javascript that is populated ahead of time by a table (basically just turning a table into a Javascript array), then, a dropdown value is referenced for the "score" column of the table.

var pointsGrid=[];

// First column is the primary key in a table with the same layou
// Second column is the name of the move
// Third column is the score
pointsGrid.push(['1',"Run",0.1]);
pointsGrid.push(['2',"Jump",0.5]);
pointsGrid.push(['3',"Twist",0.9]);

<select id="moveSelect">
  <option value="1">Run</option>
  <option value="2">Jump</option>
  <option value="3">Twist</option>
</select>

My question is during the onChange event, when I read the value of the dropdown, how do I reference the array by string, instead of by number?

For example: pointsGrid["1"] not pointsGrid[1], like in pointsGrid["StringKey"]? It keeps going back to pointsGrid[1] which is pulling the wrong score value.

Thank you in advance, Dan Chase

4
  • I think you want an Object, not an Array. Arrays are Objects which are specialized for sequential, data. In any case, you can use either a string or a number with bracket notation [stringOrNumber]. A number will be converted to a string. Commented May 7, 2017 at 6:26
  • var pointsGrid[]; is a syntax error. I think you're missing an equals-sign? Commented May 7, 2017 at 6:28
  • Raymond, corrected the typo, thank you. In the program it's correct. Commented May 7, 2017 at 6:30
  • Aluan, thank you as well! Commented May 7, 2017 at 6:39

1 Answer 1

2

Arrays number-indexed data structures. Use objects instead.

var pointsGridObj = {}
pointsGridObj["1"] = ["Run", "0.1"]
pointsGridObj["2"] = ["Jump", "0.5"]
pointsGridObj["3"] = ["Twist", "0.9"]

Or if you have the triples as an array,

pointsGridobj = {}; 
for(var i=0; i<pointsGrid.length; i++) {
  pointsGridobj[pointsGrid[i][0]] = pointsGrid.slice(1,3);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.