javascript 中 -x 和 x 之间的随机元素
Random element between -x and x in javascript
您好,我想在 JavaScript 中生成一个介于 -x 和 x 之间的随机数。
这就是我的 :
function randomInt(nb){
let absoluteVal = Math.ceil(Math.random()*nb)
let sign = Math.floor(Math.random()*2)
return sign == 1 ? absoluteVal*(-1) : absoluteVal;
}
console.log(randomInt(4))
可以用,但不够优雅。
我想知道是否有人知道更好的解决方案。
提前致谢。
例如 n = 4
,它生成这个值:
-4 -3 -2 -1 0 1 2 3 4
总共 9
个元素。通过使用正值,它生成 0
... 8
,偏移量为 -4
.
function randomInt(n) {
return Math.floor(Math.random() * (2 * n + 1)) - n;
}
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
.as-console-wrapper { max-height: 100% !important; top: 0; }
使用 Math.random()
(returns 0 和 1 之间的随机数)允许您这样做(使用 Math.ceil()
用于将数字四舍五入到下一个最大整数)
function randomInt(nb){
return Math.ceil(Math.random() * nb) * (Math.round(Math.random()) ? 1 : -1)
}
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
更多关于 Math.ceil()
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/ceil
更多关于 Math.random()
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
您好,我想在 JavaScript 中生成一个介于 -x 和 x 之间的随机数。 这就是我的 :
function randomInt(nb){
let absoluteVal = Math.ceil(Math.random()*nb)
let sign = Math.floor(Math.random()*2)
return sign == 1 ? absoluteVal*(-1) : absoluteVal;
}
console.log(randomInt(4))
可以用,但不够优雅。 我想知道是否有人知道更好的解决方案。 提前致谢。
例如 n = 4
,它生成这个值:
-4 -3 -2 -1 0 1 2 3 4
总共 9
个元素。通过使用正值,它生成 0
... 8
,偏移量为 -4
.
function randomInt(n) {
return Math.floor(Math.random() * (2 * n + 1)) - n;
}
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
.as-console-wrapper { max-height: 100% !important; top: 0; }
使用 Math.random()
(returns 0 和 1 之间的随机数)允许您这样做(使用 Math.ceil()
用于将数字四舍五入到下一个最大整数)
function randomInt(nb){
return Math.ceil(Math.random() * nb) * (Math.round(Math.random()) ? 1 : -1)
}
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
更多关于 Math.ceil()
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/ceil
更多关于 Math.random()
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random