简体   繁体   中英

innerHTML from Javascript Array

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.

var arr = [
    'There are ' + i + ' dogs in the yard.',
    'There are ' + i + ' pigs in the yard.',
    'There are ' + i + ' birds in the yard.',
    'There are ' + i + ' cats in the yard.',
    'There are ' + i + ' rabbits in the yard.',
    'There are ' + i + ' snakes in the yard.'
];

Update: Also, place your <script> somewhere below the fudge element. Currently the script is running before fudge exists.


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.

var animals = ['dogs','pigs','birds','cats','rabbits','snakes'];

function makeString() {
    var animal = animals[Math.floor(Math.random() * animals.length)],
        qty = Math.floor(Math.random() * 6) + 1;

    return "There are " + qty + " " + animal + " in the yard.";
}

makeString(); // "There are 3 dogs in the yard."

You could also take care of the singular/plural grammar value when the qty is 1 .

var animals = ['dog','pig','bird','cat','rabbit','snake'];

function makeString() {
    var animal = animals[Math.floor(Math.random() * animals.length)],
        verb = 'is',
        qty = Math.floor(Math.random() * 6) + 1;

    if (qty !== 1) {
        animal += 's';
        verb = 'are';
    }

    return "There " + verb + " " + qty + " " + animal + " in the yard.";
}

makeString(); // "There is 1 dog in the yard."

I assume that you want to use the variable i to create the strings, not just the letter i . As you use quotation marks around the strings, the variable isn't part of the string.

Instead of:

"'There are ' + i + ' dogs in the yard.'"

just use:

'There are ' + i + ' dogs in the yard.'

or:

"There are " + i + " dogs in the yard."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM