Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/418.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 获取随机选择的JSON对象中的所有值_Javascript_Json_Object_Random - Fatal编程技术网

Javascript 获取随机选择的JSON对象中的所有值

Javascript 获取随机选择的JSON对象中的所有值,javascript,json,object,random,Javascript,Json,Object,Random,我正在从json调用中检索对象列表。它们是带有“Author”和“Text”值的引号。这是一个小样本 0: author: "Thomas Edison" text: "Genius is one percent inspiration and ninety-nine percent perspiration." __proto__: Object 1: author: "Yogi Berra" text: "You can

我正在从json调用中检索对象列表。它们是带有“Author”和“Text”值的引号。这是一个小样本

0:
author: "Thomas Edison"
text: "Genius is one percent inspiration and ninety-nine percent perspiration."
__proto__: Object
1:
author: "Yogi Berra"
text: "You can observe a lot just by watching."
__proto__: Object
然后我从列表中选择一个随机对象。我不知道如何从所选对象获取这两个值。我可以分别获得文本和作者,但我似乎无法同时获得它们

这些确实有效

data[ Math.floor(Math.random() * data.length) ]['text']
data[ Math.floor(Math.random() * data.length) ]['author']
我试过这些,但都不管用

data[ Math.floor(Math.random() * data.length) ]['author','text']
data[ Math.floor(Math.random() * data.length) ]['author'],['text']

提前感谢

您可以先获取对象,然后获取文本和作者值:

var obj = data[ Math.floor(Math.random() * data.length) ];

console.log(obj.text, obj.author);
但是使用这个:

data[ Math.floor(Math.random() * data.length) ]['text']
data[ Math.floor(Math.random() * data.length) ]['author']

可能会给你一个错误的
(文本,作者)
对,例如,它可能会给你一对
(“你可以通过观看观察很多东西。”,“托马斯·爱迪生”)
,这是不正确的,因为获取文本时选择的对象可能与获取作者时选择的对象不同,这是因为调用两次
Math.floor(Math.random()*data.length)
可能会为每次调用提供不同的结果。

在您的方法中,您为每个作者和引用选择生成随机选择。将随机选择存储在另一个变量中,然后从数组中选择该索引

import random
class Quote:
  def __init__(self, author, quote):
    self.author = author
    self.quote = quote

# Get the quotes list from the api call
quote1=Quote('Thomas Edison','Genius is one percent inspiration and ninety-nine percent perspiration.')
quote2=Quote('Yogi Berra','You can observe a lot just by watching.')
quotesList=[quote1,quote2]
####

#Using random number generator to get random choce less than max lenght of fetched list
maxListLen=len(quotesList)-1
randomChoice=random.randint(0, maxListLen)

print(quotesList[randomChoice].author,' ',quotesList[randomChoice].quote)