【问题标题】:getting a random value of object property and storing to variable获取对象属性的随机值并存储到变量
【发布时间】:2018-05-21 21:07:15
【问题描述】:

我试图通过将属性与我通过 .text() 从列表项中获得的值进行比较,从对象属性中获取随机值。之后我尝试将结果存储到一个跨度。

我试图找到电视或动物的第一个属性(或将来添加的任何其他属性),然后是简单、中等或硬的属性

不确定函数 displayWord 是否正确,或者我可能遗漏了其他内容。

这是代码的其他一些相关部分,以查看变量所指的内容。 https://jsfiddle.net/peliudzemas/0fqbgo9k/1/

let result = "";
let charadesList = {
  tv : {
    easy : ['Harry Potter', 'James Bond', 'transformers'],
    medium : ['the planet of The Apes', 'Inception', 'finding nemo'],
    hard : ['taken', 'alladin', 'cast away', 'schindler\'s list']
          },

  animals : {
    easy : ['chicken', 'mouse', 'dog'],
    medium : ['lion', 'elephant', 'giraffe'],
    hard : ['monkey', 'panda', 'mole']
  }
}

function displayWord(obj, value1, value2) {
  for (var p in obj) {
    if (obj.p == value1) {
      for (var pp in obj.p) {
        if (obj.p.pp == value2) {
          result += obj.p.pp[Math.floor(Math.random()*obj.p.pp.length)];
        }
      }
    }
  }
  $('#word').append(result);
}
$(document).ready(function () {
   displayWord(charadesList, selectCategory, selectLevel);
});

【问题讨论】:

    标签: javascript object random


    【解决方案1】:

    不确定您要做什么,但如果您知道要使用的道具 - 在上面的示例中,您知道 - 这个:

    function getRandomWord(obj,val1,val2) {
        try {
            return obj[val1][val2][Math.floor(Math.random() * obj[val1][val2].length)];
        } catch {
            return null;
        }
    }
    
    function {
        let randomWord = getRandomWord(...params)
        if (randomWord)
            $('#word').append(result);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-23
      • 1970-01-01
      • 1970-01-01
      • 2013-07-08
      • 2011-09-30
      • 2018-05-03
      • 1970-01-01
      • 2019-11-13
      相关资源
      最近更新 更多