Javascript 随机偏移数组值
如果我有Javascript 随机偏移数组值,javascript,arrays,random,Javascript,Arrays,Random,如果我有 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] 必须有更好的方法来做到这一点 // This gives you an array with 4 items all collected using Math.random() var
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]
必须有更好的方法来做到这一点
// 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]
然后,您可以在计算中使用键
(索引):
// 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 = [];
for ( var i = 0; i < 4; i++ ) {
nums.push( /*something*/ );
}
var nums=[];
对于(变量i=0;i<4;i++){
推(/*某物*/);
}
但是你会得到一个封闭的作用域。Math.random()基本上用于生成0到1之间的随机十进制数。因此,如果您对获取整数元素感兴趣,请根据需要使用Math.floor(Math.random())或Math.ceil(Math.random())或Math.round(Math.random()) 您可以使用 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);
在
如果你不想使用ECMAScript 5,你也可以使用
for
循环。你能描述一下你需要这些数字做什么吗?为什么。toFixed
似乎OP需要数组中的数字?这就是+
的功能。如果你问我,奇怪的四舍五入方式。。。为什么不:Math.round(num*100)/100
而不是键入casting我不明白使用toFixed
是一种多么巧妙的方法。因为有一次它比起来非常慢,把一个数字变成一个字符串然后又变成一个数字是很奇怪的??
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);