洗牌算法,输入数字,获取随机数

本文展示了如何在JavaScript中创建一个名为`SuperArray`的类,该类继承自Array并添加了`shuffle`方法,用于实现数组元素的随机洗牌。此外,还演示了如何使用`shuffle`方法结合回调函数进行条件筛选,如筛选出数组中奇数位置的元素。这为JavaScript数组操作提供了更灵活的扩展功能。
摘要由CSDN通过智能技术生成
class SuperArray extends Array {
  shuffle() {
    // 洗牌算法
    for (let i = this.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [this[i], this[j]] = [this[j], this[i]];
    }
  }
}

const a = new SuperArray(1, 2, 3, 4, 5);
console.log(a instanceof Array); // true
console.log(a instanceof SuperArray); // true
console.log(a); // SuperArray(5) [ 1, 2, 3, 4, 5 ]
a.shuffle();
console.log(a); // SuperArray(5) [ 5, 4, 2, 3, 1 ]
const a2 = a.shuffle(x => !!(x % 2)); // SuperArray(5) [ 1, 3, 5, 4, 2 ]

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值