0

如果我有

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

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

所以我最终得到了类似的东西:

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

必须有更好的方法来做到这一点......

4

3 回答 3

0

你可以做这样的事情使用Array.prototype.map

Javascript

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);

jsfiddle 上

for或者,如果您不想使用 ECMAScript 5 ,可以使用循环

于 2013-08-02T13:21:06.320 回答
0

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

于 2013-08-02T13:07:07.063 回答
0
// 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]

然后,您可以在计算中使用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(){});

基本上和写法一样:

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

但是你会得到一个封闭的范围。

于 2013-08-02T12:59:43.413 回答