2012-05-05 8 views
1

配列からJavascriptのコンテキストを保持しようとしています。この仕事をする方法はありますか?またはよりエレガントな方法ですか?Javascriptの配列innerHTML

例:

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

?この場合、「コンテキスト」は何を意味しますか? –

+0

私は配列からjavascriptを取ろうとしていて、innerHTML ...またはアラートなどでそのコードを使用できるようにしようとしています。 – Stephen

答えて

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

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

2つのこと:あなたが揺れます。私はばかだ。ありがとう。 – Stephen

1

私はあなたが、文字列だけでなく、手紙iを作成するために、変数iを使用することを前提としています。文字列の前後に引用符を使用するので、変数は文字列の一部ではありません。

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

だけで使用します:代わりの

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

か:あなたは何をしようとしている

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