_.sample
Gets a random element from array
.
- // Underscore/Lodash
- const array = [0, 1, 2, 3, 4]
- const result = _.sample(array)
- console.log(result)
- // output: 2
- // Native
- const array = [0, 1, 2, 3, 4]
- const sample = arr => {
- const len = arr == null ? 0 : arr.length
- return len ? arr[Math.floor(Math.random() * len)] : undefined
- }
- const result = sample(array)
- console.log(result)
- // output: 2
Browser Support for Array.prototype.length() and Math.random()
✔ | ✔ | 1.0 ✔ | ✔ | ✔ | ✔ |
当前内容版权归 you-dont-need 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 you-dont-need .