简体   繁体   English

随机偏移数组值

[英]Randomly Offset Array Values

If I have 如果我有

var numbs = [1, 2, 3, 4]

var new numbs = [1 + Math.random() * 2 - 1, 2 + '' , 3 + etc....

So I end up with something like: 所以我最终得到这样的东西:

var new numbs = [.877, 2.166, 2.456, 4.235] 

There has to be a better way to do this... 必须有更好的方法来做到这一点...

// This gives you an array with 4 items all collected using Math.random()
var nums = Array.apply(null, Array(4)).map(function(v, key) {
    return Math.round(Math.random() * 100) / 100;
});
nums; // [0.64, 0.35, 0.36, 0.44]

You can then use key (the index) in your calculation: 然后,您可以在计算中使用key (索引):

// This gives you an array with 4 items all collected using Math.random()
var nums = Array.apply(null, Array(4)).map(function(v, key) {
    return key + Math.round(Math.random() * 100) / 100;
});
nums; // [0.36, 1.52, 2.35, 3.89]

var nums = Array.apply(null, Array(4)).map(function(){});

is basically the same as writing: 基本上与写作相同:

var nums = [];
for ( var i = 0; i < 4; i++ ) {
     nums.push( /*something*/ );
} 

But you will get a closed scope. 但是,您将获得封闭范围。

Math.random()基本上用于生成0到1之间的随机十进制数。因此,如果您对获取整数元素感兴趣,请使用Math.floor(Math.random())或Math.ceil(Math.random())或Math.round(Math.random())根据您的要求。

You could do something like this using Array.prototype.map 您可以使用Array.prototype.map做类似的事情

Javascript Java脚本

function randomBetween(min, max) {
    return Math.random() * (max - min) + min;
}

var numbs = [1, 2, 3, 4],
    numbsOffset = numbs.map(function (value) {
        return +(value + randomBetween(-1, 1)).toFixed(2);
    });

console.log(numbsOffset);

On jsfiddle jsfiddle上

Or you can use a for loop if you don't want to use ECMAScript 5 或者for如果您不想使用ECMAScript 5,也可以使用for循环

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM