将 Python 翻译成 JavaScript ߞ清单?
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
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
Can anyone help me write this in JavaScript? I've got most of my program written into JavaScript but specifically how to get a list with lists in it written in JavaScript has me puzzled. I'm new to programming in general, so thanks for putting up with my questions. :D
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
首先,我想说的是
for i in range(1):
行是没有用的。它只会执行一次内容,并且您没有使用i
。无论如何,您发布的代码在 JavaScript 中进行一些调整后应该可以正常工作。首先,您需要重新实现
random.choice
。你可以使用这个:之后,就很简单了:
First of all, I'd like to say that that
for i in range(1):
line is useless. It'll only execute the contents once, and you're not usingi
.Anyway, the code you posted should work fine with a few tweaks in JavaScript. First you'll need to reimplement
random.choice
. You could use this:Now after that, it's simple:
您也可以在 JavaScript 中创建一个列表,如下所示:
因为当您编写代码时JavaScript
您实际上正在创建一个具有两个属性
first
和second
的 JavaScript 对象,其值是一个列表(或数组),每个属性都有 2 个元素。正如您在 icktoofay 答案中看到的那样,这工作得很好,因为这是一个 JavaScript 对象,您可以使用此语法来检索它们
You can ( also ) create a list in with list in it in JavaScript like this:
Because when you code in JavaScript
You're actually creating a JavaScript object with two properties
first
andsecond
whose values are a list ( or array ) with to elements each. This works just fine as you can see in icktoofay answerSince that's a JavaScript object you could use this syntax to retrieve them
考虑使用 json 模块来转换数据结构Python 到 JSON 格式(这是有效的 Javascript)——反之亦然,如果您需要的话。例如:
如您所见,在这种情况下,“翻译”只是一个身份(字典条目 [[in Python]] / 对象属性 [[in Javascript]] 中顺序的更改是无关紧要的,因为 Python 的字典都不是JS 的对象也没有任何“排序”的概念;-)。
Consider using the json module to translate data structures from Python to JSON format (which is valid Javascript) -- and viceversa, if you ever need to. For example:
As you see, in this case the "translation" is just about an identity (the change of ordering in the dictionary entries [[in Python]] / object attributes [[in Javascript]] is irrelevant, as neither Python's dicts nor JS's objects have any concept of "ordering";-).