检查随机化后数组元素的位置是否相同

时间:2017-03-16 12:13:51

标签: javascript jquery arrays

我有一个包含10个元素的数组,我在窗口加载的其他数组中随机选择6个元素。我不想让新数组中任何元素的位置与之前的页面刷新相同。我该怎么做?

var tempArray = [1,2,3,4,5,6,7,8,9,10]; //inital array with 10 elements
var newArray = []; //array where random 6 elements will be pushed from tempArray
//randomize function
function randomNoRepeats(array) {
      var copy = array.slice(0);
      return function() {
        if (copy.length < 1) { copy = array.slice(0); }
        var index = Math.floor(Math.random() * copy.length);
        var item = copy[index];
        copy.splice(index, 1);
        return item;
      };
    };
var chooser = randomNoRepeats(tempArray);
for(var i=1; i<7; i++){
    newArray.push(chooser());
}
newArray = [4,7,9,2,10,1] //Suppose I get this as newArray
newArray = [2,1,5,8,10,3] //On refresh suppose 10 occurs at the same position as previous. Need to avoid this.

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您必须将tempArray存储在localStorage中并调用您的函数。

var localArray = localStorage.getItem('tempArray');
if (localArray == null) {
    localStorage.setItem('tempArray', JSON.stringify(tempArray));
    localArray = tempArray;
} else {
    localArray = JSON.stringify(localArray)
}
randomNoRepeats(localArray);

在randomNoRepeats()函数结束后调用CheckRandom()函数;

function CheckRandom() {
    for (var i = 0,
            var max = newArray.length; i < max; i++) {
        if (newArray[i] == localArray[i]) {
            randomNoRepeats(localArray);
        }
    }
    localStorage.setItem('tempArray', JSON.stringify(newArray));
}