把Python翻译成JavaScript列表?

2024-05-19 12:04:53 发布

您现在位置:Python中文网/ 问答频道 /正文

octopusList = {"first": ["red", "white"],
            "second": ["green", "blue", "red"],
            "third": ["green", "blue", "red"]}
squidList = ["first", "second", "third"]

for i in range(1):
    squid = random.choice(squidList)
    octopus = random.choice(octopusList[squid])

print squid + " " + octopus

有人能帮我用JavaScript写这个吗?我用JavaScript写了一个列表,但我很困惑。一般来说,我不熟悉编程,所以谢谢你提出我的问题。:天


Tags: forrandomgreenblueredjavascriptsquidfirst
3条回答

...specifically how to get a list with lists in it written in Javascript has me puzzled.

您可以(也)在中创建一个包含列表的列表,如下所示:

var listWithList = [["a,b,c"],["d,"e","f"], ["h","i","j"]]

因为当你用JavaScript编写代码时

^{pr2}$

实际上,您正在创建一个JavaScript对象,它有两个属性first和{},它们的值是一个列表(或数组),每个属性都有to元素。正如你在icktoofay的答案中所看到的,这个方法很好

因为这是一个JavaScript对象,所以可以使用此语法来检索它们

listOne = o.first;
listTwo = o.second;

首先,我想说for i in range(1):行是没有用的。它只执行一次内容,而您不使用i。在

不管怎样,你发布的代码在JavaScript中稍作调整就可以正常工作了。首先需要重新实现random.choice。你可以用这个:

function randomChoice(list) {
    return list[Math.floor(Math.random()*list.length)];
}

在那之后,很简单:

^{pr2}$
js> octopusList = {"first": ["red", "white"],
               "second": ["green", "blue", "red"],
               "third": ["green", "blue", "red"]}

js> squidList = ["first", "second", "third"]
first,second,third

js> squid = squidList[Math.floor(Math.random() * squidList.length)]
third

js> oct_squid = octopusList[squid]
green,blue,red

js> octopus = oct_squid[Math.floor(Math.random() * oct_squid.length)]
blue

相关问题 更多 >

    热门问题