随机启动勾选

时间:2018-01-30 06:28:43

标签: javascript arrays typescript underscore.js

我想创建整数的勾选旋转。

例如,我在数组中有数字列表:

let array = [
    1,2,3,4,5,6,7
]

然后找一个随机的开始。

例如

let random_start = 4

现在滴答结果应为:

console.log(this.tickoff(array,random_start))
  

// 4,5,6,7,1,2,3

3 个答案:

答案 0 :(得分:1)

如果random_start是您要开始的值:

array = [1, 2, 4, 5, 6, 7, 8];
random_start = 4;

function tickoff(arr, startValue) {
  indexOf = arr.indexOf(startValue);
  str = "";
  if (indexOf == -1) {
    return str;
  }
  i = indexOf;
  while (i != indexOf - 1) {
    if (i >= arr.length) {
      i = 0;
    }
    str += arr[i] + ",";
    i++;
  }
  str += arr[i];
  return str;
}

console.log(tickoff(array, random_start));

如果random_start是元素(从1开始),您想要从:

开始

array = [1, 2, 3, 5, 6, 7, 8];
random_start = 4;

function tickoff(arr, startElem) {
  str = "";
  if (startElem < 1 || startElem > arr.length) {
    return str;
  }
  i = startElem - 1;
  while (i != startElem - 2) {
    if (i >= arr.length) {
      i = 0;
    }
    str += arr[i] + ",";
    i++;
  }
  str += arr[i];
  return str;
}

console.log(tickoff(array, random_start));

答案 1 :(得分:1)

这项工作很好。

function tickOff(array, random)
{
    var result = array.splice(random,array.length-random);
    return result.concat(array);
}

var array = [1,2,3,4,5,6,7];
var index = Math.floor(Math.random()*array.length), value = array[index];
console.log("Tick off with random index : "+index+" Result : "+tickOff(array, index).join(","));

var array = [1,2,3,4,5,6,7];
var value = Math.floor(Math.random()*array.length)+1, index = array.indexOf(value);
console.log("Tick off with random value : "+value+" Result : "+tickOff(array, index).join(","));

答案 2 :(得分:0)

试试这个。

&#13;
&#13;
let array = [
    1,2,3,4,5,6,7
]
let newArray=[];
let random_start = 3;
for(i=0; i<array.length; i++, random_start++){
  if(random_start==array.length){
      random_start=0;
  }
  newArray.push(array[random_start]);
}
console.log(newArray);
&#13;
&#13;
&#13;