Warm tip: This article is reproduced from serverfault.com, please click

其他-如何在javascript中生成波动为1的随机数数组?

(其他 - How can I generate an array of random numbers that fluctuate by 1 in javascript?)

发布于 2020-11-29 14:19:29

我希望能够在javascript中生成以下数组(或类似的东西):

[
  52, // random number 0-100
  53, // random +1 or -1
  54, // random +1 or -1
  53, // random +1 or -1
  52, // random +1 or -1
  53, // random +1 or -1
  52, // random +1 or -1
  51, // random +1 or -1
  50, // random +1 or -1
  51, // random +1 or -1
  // etc., etc., etc.
]

我怎样才能做到这一点?

我已经尝试过了,但是我总是得到一个随机数,后面只有1和-1:

Array(50).fill(0).map((v, i, a) => i !== 0 ? (Math.round(Math.random()) ? a[i-1] + 1 : a[i-1] - 1) : Math.floor(Math.random() * 101))
Questioner
Nathan Chu
Viewed
0
Alan Omar 2020-11-29 23:42:52

这可能会有所帮助:

function randomGenerator(size) {
    let result = [];
    let firstValue = Math.round(Math.random() * 100);
    result.push(firstValue);
    
    for (let i=0;i<size-1;i++){
        firstValue += Math.random() > 0.5 ? 1:-1;
        result.push(firstValue)
    }
    return result;
}

console.log(randomGenerator(10));
console.log(randomGenerator(13));

或者,如果你更喜欢使用功能,则可以利用默认值和逗号运算符

const randGenerator = (size = 13,init = Math.round(Math.random() *100)) => 
Array(size).fill(0).map(e => (init += Math.random() > 0.5 ? 1:-1,init))

console.log(randGenerator(10))
console.log(randGenerator(13))