Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

数组随机排列 #18

Open
xxxgitone opened this issue Aug 28, 2017 · 0 comments
Open

数组随机排列 #18

xxxgitone opened this issue Aug 28, 2017 · 0 comments

Comments

@xxxgitone
Copy link
Owner

xxxgitone commented Aug 28, 2017

数组随机排列,一般用于随机播放,图片随机展示

// 方法一
function shuffle (arr){
  for(var i = 0; i < arr.length; i++ ){
     var rand = parseInt(Math.random() * arr.length);
     var temp = arr[rand];
     arr[rand] = arr[i];
     arr[i] = temp;
  }
  return arr;
}

// 方法二
function getRandomIndex (min, max) {
   return Math.floor(Math.random() * (max - min + 1) + min)
}

function shuffle1 (arr) {
  let newArr = arr.slice()
  for (let i = 0; i < newArr.length; i++) {
    let j = getRandomIndex(0, i)
    let temp = newArr[i]
    newArr[i] = newArr[j]
    newArr[j] = temp
  }
  return newArr
}

// 方法三
function shuffle(a) {
    var j, x, i;
    for (i = a.length; i; i--) {
        j = Math.floor(Math.random() * i);
        x = a[i - 1];
        a[i - 1] = a[j];
        a[j] = x;
    }
    return a;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant