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

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 に答える