繁体   English   中英

来自Javascript Array的innerHTML

[英]innerHTML from Javascript Array

我正在尝试从数组中保留Javascript上下文。 有没有办法让这项工作? 还是更优雅的方式?

例:

<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>

摆脱外部双引号。

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.'
];

更新:另外,将<script>放在fudge元素下面的某个位置。 目前,脚本在fudge存在之前运行。


如果您希望更新字符串以及将来对变量的更新,那将无效。 您需要生成一个新字符串。

你可以做一个功能。

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."

qty1时,您还可以处理单数/复数语法值。

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来创建字符串,而不仅仅是字母i 当您在字符串周围使用引号时,该变量不是字符串的一部分。

代替:

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

只需使用:

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

要么:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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