0

Knowing that Object.keys() numerically indexes the keys of associative arrays, I expected that the returned keys could be used in other variables.

Specifically, using the variable plant=genusSpecies.(keys[2]) to load my slideshow photos results in an undefined variable per the Google Chrome Inspect Console. I also tried plant=genusSpecies.keys[2], which didn't work. I'm not sure if there's a syntax error, or something else. As an aside,document.write(keys[2]) works as expected, displaying file names beneath where the photos should be. Please advise. Thanks.

var genusSpecies={"Acalypha_deamii":["Acalypha_deamii.png","Acalypha_deamii1.png","Acalypha_deamii2.png","Acalypha_deamii3.png"],"Acalypha_ostryifolia":["Acalypha_ostryifolia.png","Acalypha_ostryifolia1.png","Acalypha_ostryifolia2.png"],"Acalypha_rhomboidea":["Acalypha_rhomboidea1.png","Acalypha_rhomboidea2.png"],"Acer_ginnala":["Acer_ginnala.png"],"Acer_negundo":["Acer_negundo1.png","Acer_negundo2.png"]}

var curimg=0

var keys = Object.keys(genusSpecies)
document.write(keys[2]) //<!--Displays plant name beneath photos-->
var plant=genusSpecies[keys[2]] //<!--Supposed to load ALL values of specified key, but doesn't work-->

function swapImage()
{
   document.getElementById("slide").setAttribute("src", "/Users/jeffmancini/Desktop/xampp/htdocs/cnc/images/plants/"+plant[curimg]);
   curimg=(curimg<plant.length-1)? curimg+1 : 0; 
   timer = setTimeout("swapImage()",4000);
}

function stopShow()
{
  clearTimeout(timer);
}

function runShow()
{
  swapImage();  
}
<!DOCTYPE html>
<html>
<head>
<title>Slideshow</title>
<!--Slideshow script (ALL photos of each plant iterated from an array of key/value pairs defined by the variable "genusSpecies")-->
<!--Updating the variable "genusSpecies" updates the slideshow-->
</head>

<body onLoad="runShow()">
<img id="slide" onmouseover="stopShow()" onmouseout="runShow()" src="" alt="Plant photo">

</body>
</html>
Ran Marciano
  • 1,431
  • 5
  • 13
  • 30
Jeff
  • 179
  • 10
  • 1
    `genusSpecies[keys[2]]` – tkausl Nov 18 '20 at 20:09
  • 3
    Does this answer your question? [JavaScript property access: dot notation vs. brackets?](https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets) – ASDFGerte Nov 18 '20 at 20:09
  • tkausl is right. Also, don't use for comments in javascript, use // for single lines or /* ... */ for multilines. – Ollie Nov 18 '20 at 20:12
  • genusSpecies [keys[2]] works! Thanks, tkausl!!! – Jeff Nov 18 '20 at 20:21

0 Answers0