1

我正在尝试从数组中保留 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>
4

2 回答 2

2

摆脱外部双引号。

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

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."
于 2012-05-05T20:11:19.937 回答
1

我假设您想使用变量i来创建字符串,而不仅仅是字母i。当您在字符串周围使用引号时,变量不是字符串的一部分。

代替:

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

只需使用:

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

或者:

"There are " + i + " dogs in the yard."
于 2012-05-05T20:12:44.740 回答