码迷,mamicode.com
首页 > 编程语言 > 详细

js数组操作-打乱数组

时间:2015-05-13 12:15:44      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:

<style>
  html, body { margin: 0; padding: 0;}
  div span { display: inline-block; width: 25px; height: 25px; background: red; }
</style>
<div id="wrap">
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
</div>

  

<script>
  function shuffle(aArr) {
    var iLength = aArr.length
      , i = iLength
      , nTemp
      , iRandom;
    while ( i-- ) {
      if (i !== (iRandom = Math.floor(Math.random()*iLength))) {
        nTemp = aArr[i];
        aArr[i] = aArr[iRandom];
        aArr[iRandom] = nTemp;
      };
    };
    return aArr;
  };
  var oSpans = document.getElementById("wrap").getElementsByTagName("span");
  var arr2 = [1, 2, 3, 4, 5, 6];
  var flag = true;
  for (var i = 0, len = oSpans.length; i < len; i++) {
    oSpans[i].index = i;
    oSpans[i].onclick = function() {
      var t = parseInt(Math.random(6)); // 目标坐标
      var target = arr2[t]; // 目标值
      arr2.splice(t, 1); // 将目标值从数组中删除
      shuffle(arr2); // 数组随机排列
      var index = this.index; // 获得点击后span的index
      arr2.splice(index, 0, target); //此时将target插入到arr2中
      for (var i = 0, len = oSpans.length; i < len; i++) {
        oSpans[i].innerHTML = arr2[i];
      };
    };
  };
</script>

  

js数组操作-打乱数组

标签:

原文地址:http://www.cnblogs.com/manchun/p/4499934.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!