获取一组随机下标(相邻两个不重复)的数组

  1. function getRandomNumByRange(start, end) {
  2. return Math.floor(Math.random() * (end - start) + start);
  3. }
  4. // 获取一组随机下标的数组
  5. function getRandomCardBg(len) {
  6. const res = [];
  7. for (let i = 0; i < len; i++) {
  8. const temp = this.getRandomNumByRange(0, 5);
  9. if (i > 0) {
  10. if (temp === res[i - 1]) {
  11. for (let j = 0; j < 10000; j++) {
  12. const temp2 = this.getRandomNumByRange(0, 4);
  13. if (temp2 !== res[i - 1]) {
  14. res.push(temp2);
  15. break;
  16. }
  17. }
  18. } else {
  19. res.push(temp);
  20. }
  21. } else {
  22. res.push(temp);
  23. }
  24. console.log('temp res', res)
  25. }
  26. return res;
  27. }
  28. var a = getRandomCardBg(10);
  29. console.log('------ a', a);