Nad*_*eid -1 html javascript variables json
在控制台中,我似乎无法记录"男性"或"女性"的值.应该是这样的console.log(choice[0].a).它不记录变量的值string.以下是我的尝试,谢谢你的时间.
<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>
Run Code Online (Sandbox Code Playgroud)
console.log(choice[0][string]);
Run Code Online (Sandbox Code Playgroud)
您的对象中没有字符串属性,而是与该字符串包含的键相关的值.
有点短:
console.log(Math.round(Math.random())?"male":"female");
Run Code Online (Sandbox Code Playgroud)