2017-08-02 29 views
-1

コンソールでは、「男性」または「女性」の値を記録できないようです。それはconsole.log(choice[0].a)のようなものでなければなりません。変数stringの値は記録されません。以下は私が試したことです、あなたの時間をありがとう。javascript変数を読み取ることができません

<html> 
    <head> 
     <script type="text/javascript"> 
      var string = ""; 
      var randoml = "ab"; 
      while (string.length < 1) { 
       string += randoml[Math.floor(Math.random() * randoml.length)]; 
      } 
      console.log(string); 
      data = '[{"a" : "male", "b" : "female"}]'; 
      var choice = JSON.parse(data); 
      console.log(choice[0].string); 
     </script> 
    </head> 
</html> 
+1

は、なぜあなたはそれをJSON.parseする文字列を作成するのですか?オブジェクトを作成するだけで、はるかに簡単になります – baao

答えて

6
console.log(choice[0][string]); 

Theresのあなたのオブジェクトで無い文字列プロパティではなく、キーに関連する値が、その文字列が含まれています。

ビット短い:

console.log(Math.round(Math.random())?"male":"female"); 
+1

秒単位で逃しました!ニース+! – Tushar

+1

'Math.round(Math.random())'はさらに短くなります;) – Phil

+0

@philしかし、それは等しく分布しませんか? –

関連する問題