【问题标题】:Loop through object and get random item in javascript [duplicate]遍历对象并在javascript中获取随机项目[重复]
【发布时间】:2019-04-19 11:09:08
【问题描述】:

假设您有一个 Javascript 对象,该对象具有一些属性来随机显示带有背景、文本和标题的页面,您将如何在其中循环以使其每次仅在对象上显示一项?

const list = {
            b1:{
                author: 'Mozart',
                title: 'lacrimosa',
                text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
                imageURL: 'url(./assets/img/image.jpg)'
            },
            b2:{
                author: 'Choppin',
                title: 'Waltz in A minor',
                text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
                imageURL: 'url(./assets/img/image.jpg)'
            },
            b3:{
                author: 'Bach',
                title: 'Ave Maria',
                text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
                imageURL: 'url(./assets/img/image.jpg)'
            },
        }





return(
            <div className="background" style={{background: 'url(./assets/img/image.jpg)'}}>
                <div className="caption">
                    <blockquote>
                        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
                        <p> artist - <cite>Song</cite></p>
                    </blockquote>
                </div>
            </div>
        )

我尝试了 Math.random() 方法,但没有成功

【问题讨论】:

  • 你想渲染来自list对象的随机元素吗?
  • 看看this question,它解释了如何从对象中获取随机值。
  • 除了对象之外还有其他代码吗,比如使用Math.random的函数?

标签: javascript arrays reactjs loops object


【解决方案1】:

只需 3 行简单的代码即可完成此操作。

//find the length of your object
const length = Object.keys(list).length

//generate a random number that's between 0 and the length of your object
const random_number = Math.floor((Math.random() * length) + 0);

//get your random item from the object
const random_item = list[Object.keys(list)[random_number]]


console.log(random_item)

键可以是完全动态的(b1、b2、b3 可以任意命名 - 例如:b1、g4、aaa)

【讨论】:

    【解决方案2】:

    在大卫的回答中使用 Math.random() 是错误的:你最终可能会得到键 [-1]!正确的方法是使用 Math.floor(Math.random()*length)。此外,我会根据您的需要使用 Object.keys() 方法,请参阅this doc。这是一个可行的解决方案:

    const list = {
      b1: {
        author: 'Mozart',
        title: 'lacrimosa',
        text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
        imageURL: 'url(./assets/img/image.jpg)'
      },
      b2: {
        author: 'Chopin',
        title: 'Waltz in A minor',
        text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
        imageURL: 'url(./assets/img/image.jpg)'
      },
      b3: {
        author: 'Bach',
        title: 'Ave Maria',
        text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
        imageURL: 'url(./assets/img/image.jpg)'
      },
    };
    
    const keys = Object.keys(list);
    const randomIndex = keys[Math.floor(Math.random() * keys.length)];
    const item = list[randomIndex];
    console.log(item.author);

    Object.getOwnPropertyNames() 方法也适用于您的具体示例。

    【讨论】:

    • 工作就像一个魅力!谢谢
    【解决方案3】:
    const randomItem = function (obj) {
      var keys = Object.keys(obj)
      return obj[keys[ keys.length * Math.random() << 0]];
    };
    

    【讨论】:

    • 你能解释一下这里发生了什么吗?
    【解决方案4】:

    我会更好地建议(为了防止对象命名而不是 b1、b2 等的可能变化)使用 Object.keys() 方法:

    var listKeys = Object.keys(list);
    var randomIndex = Math.floor(Math.random() * listKeys.length);
    var randomObject = list[listKeys[randomIndex]];
    

    【讨论】:

      【解决方案5】:

      要么将对象转换为Array,以便您可以使用Math.random(),要么创建一个键列表,选择一个并使用它来访问对象。

      转换为Array

      const arrList = Object.keys(list).map(k => list[k]);
      const item = arrList[Math.round(Math.random() * arrList.length - 1)];
      

      使用键列表

      const keys = ['b1', 'b2', 'b3'];
      const item = list[keys[Math.round(Math.random() * keys.length - 1)]];
      

      【讨论】:

        【解决方案6】:

        您可以像这样从对象中获取随机项目

        const randomItem = list['b' + Math.floor(Math.random() * 2)]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-07-10
          • 2020-10-08
          • 2016-07-08
          • 1970-01-01
          • 2023-02-10
          • 2020-07-17
          • 2013-06-18
          相关资源
          最近更新 更多