【问题标题】:How do I randomize the outcome of an array, then link it to a conditional [closed]如何随机化数组的结果,然后将其链接到条件 [关闭]
【发布时间】:2021-03-16 19:19:50
【问题描述】:

我想随机化来自person 数组的结果。如何将它连接到 if 语句,以便它每次都随机化这个人,如果我加载它,它每次都会给我一个不同的句子。

let placea = 'Shopping Mall'
let placeb = 'Library'

let person = ['John', 'Sam', 'Ryan', 'Liam', 'David']

if (person === 'John' || person === 'Liam' || person === 'Sam') {
  console.log(`Lets go to the ${placea}`)
} else {
  console.log(`I love quiet places, lets go to the ${placeb}`)
}

【问题讨论】:

标签: javascript arrays random


【解决方案1】:

我认为您希望“人”指代数组中的随机人,而不是数组本身。

要记住的一个好技巧是如何从数组a 中获取随机元素(适用于任何非空数组):

const a = [1, 2, 3];
const randomElement = a[Math.floor(Math.random() * a.length)];

Math.random 给出从 0 到几乎 1 的随机浮点数

将它乘以数组长度,得到一个从 0 到几乎数组长度的随机浮点数

Math.floor 去掉小数,得到一个从 0 到数组长度的随机整数 - 1

let placea = 'Shopping Mall'
let placeb = 'Library'

let people = ['John', 'Sam', 'Ryan', 'Liam', 'David'];
let person = people[Math.floor(Math.random() * people.length)];

if (person === 'John' || person === 'Liam' || person === 'Sam') {
  console.log(`Lets go to the ${placea}`)
} else {
  console.log(`I love quiet places, lets go to the ${placeb}`)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    • 2018-05-15
    • 2021-02-04
    • 1970-01-01
    • 2013-02-05
    • 1970-01-01
    相关资源
    最近更新 更多