从 JavaScript 数组中获取随机项

新手上路,请多包涵
var items = Array(523, 3452, 334, 31, ..., 5346);

我如何从 items 获得随机物品?

原文由 James 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 276
2 个回答
var item = items[Math.floor(Math.random()*items.length)];

原文由 Kelly 发布,翻译遵循 CC BY-SA 4.0 许可协议

1.解决方案:定义Array原型

Array.prototype.random = function () {
  return this[Math.floor((Math.random()*this.length))];
}

这将适用于内联数组

[2,3,5].random()

当然还有预定义的数组

var list = [2,3,5]
list.random()

2.解决方案:定义接受列表并返回元素的自定义函数

function get_random (list) {
  return list[Math.floor((Math.random()*list.length))];
}

get_random([2,3,5])

原文由 Dino Reic 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题