I’m trying to preserve Javascript context from an array. Is there any way to make this work? Or a more elegant way?
EXAMPLE:
<html>
<script type="text/javascript">
var rand = Math.floor(Math.random() * 6) + 1;
var i = Math.floor(Math.random() * 6) + 1;
var arr = ["'There are ' + i + ' dogs in the yard.'","'The other day I saw ' + i + ' pigs that one lake.'","'I can't believe there were ' + i + ' birds in your yard the other day.'","'Why were there ' + i + ' cats in my front yard?'","'There are ' + i + ' rabbits in the yard.'","'There are ' + i + ' snakes in the yard.'"];
document.getElementById('fudge').innerHTML = arr[rand];
</script>
<body>
<div id='fudge'></div>
</body>
</html>
Get rid of the outer double quotes.
Update: Also, place your
<script>somewhere below thefudgeelement. Currently the script is running beforefudgeexists.If you want the strings to update with future updates to the variable, that won’t work. You’d need to generate a new string.
You could make a function instead.
You could also take care of the singular/plural grammar value when the
qtyis1.