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 编写的,但特别是如何获取一个列表,其中包含用 JavaScript 编写的列表,这让我感到困惑。一般来说,我是编程新手,所以感谢您提出我的问题。 :D
最佳答案
首先,我想说 for i in range(1):
行没有用。它只会执行一次内容,并且您没有使用 i
。
无论如何,您发布的代码在 JavaScript 中进行一些调整后应该可以正常工作。首先,您需要重新实现 random.choice
。你可以使用这个:
function randomChoice(list) {
return list[Math.floor(Math.random()*list.length)];
}
接下来就很简单了:
var octopusList = {
"first": ["red", "white"],
"second": ["green", "blue", "red"],
"third": ["green", "blue", "red"]
};
var squidList = ["first", "second", "third"];
var squid = randomChoice(squidList);
var octopus = randomChoice(octopusList[squid]);
// You could use alert instead of console.log if you want.
console.log(squid + " " + octopus);
关于javascript - 将 Python 翻译成 JavaScript——列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3261466/