js本身没有这个功能,不过我们可以对Array对象加个random属性即可达到这种效果。
上代码:
Array.prototype.random = function() {
let idx = Math.floor(Math.random() * this.length);
return this[idx];
}
let arr = ['a', 'b', 'c', 'd'];
console.log(arr.random())
console.log(arr.random())
console.log(arr.random())
执行效果如下