美文网首页
js数组乱序

js数组乱序

作者: 任无名F | 来源:发表于2017-07-26 22:04 被阅读0次
    1. 使用Array的sort方法
    Array.prototype.shuffle = function() {
        this.sort((a,b) => {
          return Math.random() * 2 - 1; // 随机返回1或-1
        });
    }
    
    1. 更高效的方法,时间复杂度为n
    Array.prototype.shuffle = function() {
        for(let t, j, i = this.length; i;) {
          j = Math.floor(Math.random() * i); // 在前i项中随机取一项,与第i项交换
          t = this[--i];
          this[i] = this[j];
          this[j] = t;
        }
    }
    

    相关文章

      网友评论

          本文标题:js数组乱序

          本文链接:https://www.haomeiwen.com/subject/upfakxtx.html