javascript - 如何访问数组中随机对象的属性?

标签 javascript arrays random javascript-objects

我有一个对象数组。它们中的每一个都具有与其他相同的属性,但具有不同的值。我想访问此数组中随机对象的属性,但只是一次 - 所以当我随机获取该对象时,它不会再出现在数组中。

因此,我创建了仅包含三个对象的数组,并创建了一个函数,该函数将通过单击按钮来调用。该函数创建 2 个变量 - 一个用于存储从 Math.random() 与数组长度的乘积中接收到的随机数,由 Math.floor() 舍入。

第二个变量存储从数组中删除的一项(每次都是随机的),应该返回它。

这个想法是每次当用户点击按钮时获得一张独特的卡片,而不是能够再次获得同一张卡片。 它有效但不完全是 - 有时,在单击按钮后,用户什么也得不到,控制台中的消息是“Uncaught TypeError: Cannot read property 'background' of undefined”。

欢迎任何建议。谢谢。

这是我的代码:

var TarotContainer = [];
TarotContainer[0] = {name: "The Fool", background: "url('theFool.jpg')"}
TarotContainer[1] = {name: "The Magician", background: "url('theMagician.jpg')"}
TarotContainer[2] = {name: "The High Priestess", background: "url('theHighPriestess.jpg')"}

function getRandomTaroCard(){
    var randomCard = Math.floor(Math.random() * TarotContainer.length); 
    var pickedRandomCard = TarotContainer.splice(randomCard, 1);
    document.getElementById('card').style.backgroundImage = pickedRandomCard[randomCard].background;
    document.getElementById('card').style.backgroundRepeat = "no-repeat";                                                         

最佳答案

来自Mozilla Javascript Reference关于 Array.prototype.splice() 返回的内容:

an array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

这意味着您必须使用 pickedRandomCard 的第一个元素 ([0])。

像这样:

var TarotContainer = [];
TarotContainer[0] = {name: "The Fool", background: "url('theFool.jpg')"}
TarotContainer[1] = {name: "The Magician", background: "url('theMagician.jpg')"}
TarotContainer[2] = {name: "The High Priestess", background: "url('theHighPriestess.jpg')"}

function getRandomTaroCard(){
    var randomCard = Math.floor(Math.random() * TarotContainer.length); 
    var pickedRandomCard = TarotContainer.splice(randomCard, 1);
    document.getElementById('card').style.backgroundImage = pickedRandomCard[0].background;
    document.getElementById('card').style.backgroundRepeat = "no-repeat";   

关于javascript - 如何访问数组中随机对象的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30759023/

相关文章:

javascript - 使用 HTML 和 JS 运行外部应用程序(vlc 播放器、文本文档、.exe)

javascript - 通过 webpack 导入 jquery 错误 - 找不到模块 : can't resolve jquery

javascript - 在网页上可见之前确定 DIV 高度的最佳方法是什么?

php - 在 mysql 中使用 WHERE 和 IN 时数组的排序问题

arrays - 为什么 Array<Any>.flatMap() 将转换闭包参数包装在可选中?

C - 将字符串保存到数组元素中

mysql Rand() 函数导致意外的多行结果

Javascript Array.push 在 get 方法中不起作用

c++ - 为什么最低()和最大()之间生成的所有随机数都等于无穷大?

来自两个不重叠范围的 Python 随机唯一值