Javascript / JSP随机排序两个相等的字符串数组

时间:2015-02-17 12:26:41

标签: javascript arrays jsp sorting

我在脚本中有一个字符串数组,我随机排序然后我将使用。然后我想用url将相同的排序数组传递给Jsp页面,但是很难,所以我想在脚本和Jsp页面中生成相同的随机数组,你能帮帮我吗?

var shuffle = ['0B', '1B', '2B', '3B', '4B', '5B', '6B', '7B', '8B', '9B', '0C', '1C', '2C', '3C', '4C', '5C', '6C', '7C', '8C', '9C', '0O', '1O', '2O', '3O', '4O', '5O', '6O', '7O', '8O', '9O', '0S', '1S', '2S', '3S', '4S', '5S', '6S', '7S', '8S', '9S'];

如果我想要的话,我怎么能平等地洗牌呢?

1 个答案:

答案 0 :(得分:0)

这是你要找的吗? 我做了两个文件。一个生成混洗数组,然后编码一个URL;并且读取该URL的一个设置了数组的顺序。

encode.php

<div id="click" onclick="encode()">Click</div>
<div id="log"></div>
<script>
// I presume both files have the same array
var items = ['hello', 'world', 'foo', 'bar'];

function encode() {
  var data = shuffle_and_encode_order(items);
  // notice: data.keys is the array containing the keys; data.values contains the values
  // we encode the order to a URL readable format
  var url = '#' + data.keys.toString() +'';
  document.getElementById('log').innerHTML = 
    data.values.toString() + '<br>' +
    '<a href="decode.php' + url + '">LINK for this order</a>';
}

// encode the order of the array (to url) 
function shuffle_and_encode_order (items) {
  // retreive the keys of the array.  So this returns [0, 1, 2, ...]
  var keys = Object.keys(items);
  // now we sort 'keys', and remember the order of that array
  var keys_sorted = shuffle(keys);
  var result = {keys: [], values: []};
  // we fill var result with the items; in the new order
  for (var i=0; i<items.length; i++) {
    result.keys.push(keys_sorted[i]);
    result.values.push(items[keys_sorted[i]]);
  }
  return result;
}

// @see http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array#2450976
function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex ;
  while (0 !== currentIndex) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }
  return array;
}
</script>

decode.php

<div id="log"></div>
<script>
// I presume both files have the same array
var items = ['hello', 'world', 'foo', 'bar'];

function decode() {
  // we read the url, everything to the right of the # symbol.
  var hash = window.location.hash.substr(1); // that substr is to remove the #.
  var keys = hash.split(',');  // makes an array of this string; separates the items by comma characters
  var values = items_set_order(items, keys);

  document.getElementById('log').innerHTML = 
    values.toString() + '<br>';
}

function items_set_order(items, keys) {
  var result = [];
  for (var i=0; i<items.length; i++) {
    result.push(items[keys[i]]);
  }
  return result;
}
window.onload = decode();
</script>