如何从嵌套在对象中的数组中选择随机项目

时间:2019-06-09 13:21:59

标签: javascript

我正在尝试一个项目,该项目将从对象的3个嵌套数组之一中选择一个随机答案。我的目标是后来知道答案来自哪个数组,所以我可以用它来知道新句子是什么。

下面的示例适用于1个数组,但是我想知道答案是一个好,坏还是疑问的答案,因此为什么要将它放在一个对象中。

编辑:下面的代码为我提供了对象的随机属性,但我需要更进一步。它旁边的评论是我尝试过的,但未定义。

const randomAnswers = {
goodAnswers: ['yes','Absolutely','certainly',"I'm sure",'HELL YES'],
maybes: ['maybe','probably','perhaps',"honestly man, i really don't 
know this one"],
badAnswers: ['LOL NO','no way man','maybe',"forget it",'HELL no','Are 
you serious?']
};
{

const init = () => {
console.log("initiated");
let answer = document.querySelector('.answer');
answer.style.opacity = 0;

setTimeout(fixSentence,3000);
//fixSentence();
}

const fixSentence = () => {
    let a = document.querySelector('.answer');
    let think = document.querySelector('.think');
    console.log('shown');
    console.log(a.textContent);
    let randomAnswer = randomAnswers[Math.floor(Math.random()*randomAnswers.length)];

    var randomProperty = function (obj) {
        var keys = Object.keys(obj)
        let random = obj[keys[ keys.length * Math.random() << 0]];
        return random/*[Math.floor(Math.random()*randomAnswers.length)]*/;
    };

    console.log(randomProperty(randomAnswers))

    let splittedSentence = a.textContent.split(" ");
    console.log(splittedSentence);
    a.textContent = `${randomAnswer}`;
    a.style.opacity = 1;
    think.style.opacity = 0;
}

init();

}

console.log(randomAnswer)的输出现在显然是未定义的,但是我无法弄清楚如何从对象的三个数组之一中选择一个随机项。

1 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

const randomAnswers = {
  goodAnswers: ['yes','Absolutely','certainly',"I'm sure",'HELL YES'],
  maybes: ['maybe','probably','perhaps',"honestly man, i really don't know this one"],
  badAnswers: ['LOL NO','no way man','maybe',"forget it",'HELL no','Are you serious?']
};

const randomNumber = function(subject) {
  return Math.floor(Math.random()*subject.length);
}

const types = Object.keys(randomAnswers);
const randomTypeNumber = randomNumber(types);
const randomType = types[randomTypeNumber];

const randomAnswerNumber = randomNumber(randomAnswers[randomType]);
const randomAnswer = randomAnswers[randomType][randomAnswerNumber];

console.log( { randomType, randomAnswer } );

您从对象中选择一个随机键,然后使用Object.keys(randomAnswers).length从该数组中选择一个随机元素,然后使用该数组的长度作为随机数。