扫码关注官方订阅号
var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g']; // 随机取得三个元素使得 var newarr = ['e', 'c', 'a'];
ringa_lee
Array.prototype.random = function () { var idx = Math.floor((Math.random()*this.length)); var n = this.splice(idx,1)[0]; return n; } var i = 0; var a = []; while(i++<3){ a.push(arr.random()) } console.log(a);
先求数组长度len,然后获得[0,len-1]之间的随机数来做索引,然后用索引去访问数组,就可以获得数组的随机元素
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
扫描下载App
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
先求数组长度len,然后获得[0,len-1]之间的随机数来做索引,然后用索引去访问数组,就可以获得数组的随机元素