我有两个按钮。例如一种随机的电影风格。 ['love','war','true']。我有这个工作。问题是,第二个按钮应该从选择的电影风格中选择随机电影。例如如果选择了“爱情”,则新的随机数将从“爱情列表” ['Noel','Titanic','Pearl Harbor']中获得。感谢您的帮助,谢谢大家... ^ _ ^ ...
>>> k = max(emails, key=emails.get)
>>> (k, emails[k])
('efg@efg.org', 3)
答案 0 :(得分:1)
使用Math.floor(Math.random() * moviesByType.length)
,您可以在数组长度范围内生成随机索引。
我维护了一部以电影类型为关键的电影词典。
单击按钮后,我们可以读取movie-type
属性,然后按类型从字典中获取列表,并从该数组中返回一个随机元素。
const movieList = {
love: ['Love1', 'Love2', 'Love3'],
war: ['War1', 'War2', 'War3'],
true: ['True1', 'True2', 'True3']
};
const getRandomMovie = (e) => {
const type = e.target.getAttribute('movie-type');
let moviesByType = movieList[type] || [];
if(moviesByType.length) {
const randomIndex = Math.floor(Math.random() * moviesByType.length);
const movie = moviesByType[randomIndex];
console.log(`${type}: ${movie}`);
}
}
document.querySelectorAll('button').forEach(btn => btn.onclick=getRandomMovie);
<button movie-type="love">
Love
</button>
<button movie-type="war">
War
</button>
<button movie-type="true">
True
</button>