将Python翻译成JavaScript——列表?

2 投票
4 回答
881 浏览
提问于 2025-04-16 01:22
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

4 个回答

1

...具体来说,我在用JavaScript创建一个包含列表的列表时感到困惑。

你可以这样在JavaScript中创建一个包含列表的列表:

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

因为当你在JavaScript中编写代码时,

o = { "first" : ["red","green"],
      "second": ["blue","white"]}

你实际上是在创建一个JavaScript对象,这个对象有两个属性 firstsecond,它们的值是各自包含两个元素的列表(或数组)。这就可以正常工作,正如你在icktoofay的回答中看到的那样。

由于这是一个JavaScript对象,你可以使用这种语法来获取它们:

listOne = o.first;
listTwo = o.second;
1
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

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

4

首先,我想说的是,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);

撰写回答