Reputation: 1042
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
Upvotes: 2
Views: 43
Reputation: 6564
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);
}
Upvotes: 2