javascript - 将 Python 翻译成 JavaScript——列表?

标签 javascript python translation

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/

相关文章:

python - 更改不正确的python路径ubuntu

virtual-machine - QEMU 如何维护从访客虚拟地址到访客物理地址的转换?

javascript - Jasmine : mocking $animate from Angular Material

单独对象的构造函数中的 JavaScript 变量隔离

javascript - 使用 Ajax POST 请求将图像和 JSON 数据发送到服务器?

python - 如何让 .grid_columnconfigure() 在框架内工作?

javascript - showModalDialog 替代方案?

python - python中的全局变量错误

java - 如何从java翻译网页?

Android 应用程序翻译不工作