将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将Python翻译成JavaScript - 列表?
首先,我想说那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);
'Math.random()'可以返回1,在这种情况下'randomChoice()'访问一个不好的索引。 – orip 2012-01-24 12:05:46
@orip:[MDN表示'Math.random'不能返回1](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/random):“返回一个浮点伪随机数字范围[0,1],即从0(包括)到**但不包括1(独占)**,然后您可以缩放到您想要的范围。 – icktoofay 2012-01-25 04:51:57
谢谢,我站在更正 – orip 2012-01-25 08:13:16
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
......具体怎么获得与Javascript编写的有我在里面列出了清单困惑。
可以(也)在列表中它在JavaScript中创建一个列表如下:
var listWithList = [["a,b,c"],["d,"e","f"], ["h","i","j"]]
因为当你的代码在JavaScript
o = { "first" : ["red","green"],
"second": ["blue","white"]}
你实际上是在制造一个具有两个属性first
和second
的JavaScript对象,其值是每个元素都有一个元素的列表(或数组)。你可以看到在icktoofay回答
由于这是一个JavaScript对象,你可以使用这个语法来检索他们这只是正常
listOne = o.first;
listTwo = o.second;
值得注意的是,这个答案是面向如果它已被翻译成JavaScript。 Python中的'{“a”:“b”,...}'语法指定了一个字典,而不仅仅是一个普通的对象。另外,要访问Python中的元素,您可以使用'myList [“first”]和'myList [“second”]'等等。最后,列表代码的列表应该在Python中工作,如果您删除'var '部分。 – icktoofay 2010-07-16 02:35:15
:) :) yeap,那是因为这个答案中的所有代码都是javascript:P not python:P我正在更新它 – OscarRyz 2010-07-16 03:35:48
考虑使用json模块从Python来JSON格式的数据结构转换(这是有效的Javascript) - 反之亦然,如果你需要的话。例如:
>>> octopusList = {"first": ["red", "white"],
... "second": ["green", "blue", "red"],
... "third": ["green", "blue", "red"]}
>>> print json.dumps(octopusList)
{"second": ["green", "blue", "red"], "third": ["green", "blue", "red"], "first": ["red", "white"]}
>>>
正如你看到的,在这种情况下,“翻译”是只是一个身份(排序的字典中的条目的变化[在Python] /对象属性[[在Javascript]是无关紧要的,因为Python的字典和JS的对象都没有任何“排序”的概念;-)。
+1为头节点 – Cole 2010-07-16 03:40:37