[英]Convert random positive values of an array to negative
我是JS新手。 我有一個混亂的數字數組,需要將數組的隨機正值轉換為負數。 那時我只知道如何隨機化數組:
var myArray = [1,2,3,4,5,6,7,8,9,10];
myArray.sort(function() {
return 0.5 - Math.random()
})
但是需要結果看起來像這樣:[8,-2,3,9,-5,-1,4,7,6,-10]
請提出建議。 謝謝!
myArray.forEach(function(i,j){
if(i>0){
var negative=i*(-1);/*convert your positive values to negative*/
myArray[j]=negative;
}
})
改良的Fisher-Yates隨機播放以隨機否定該物品
function shuffle2(arr) {
var i, j, e;
for (i = 0; i < arr.length; ++i) { // for every index
j = Math.floor(Math.random() * (arr.length - i)); // choose random index to right
e = arr[i]; // swap with current index
arr[i] = arr[i + j];
arr[i + j] = e;
if (.5 > Math.random()) // then, randomly
arr[i] = -arr[i]; // flip to negative
}
return arr;
}
現在可以做
shuffle2(myArray); // [-5, 2, 6, -7, -10, 1, 3, -4, -9, -8]
請注意,如果要在arr.length - 1
處停止循環,則需要在循環外進行最后的隨機翻轉以獲取最后一個索引
您可以使用Array.prototype.map()轉換數組以獲取隨機+/-,如下所示:
myArray = myArray.map(function(item) {
return Math.random() > 0.5 ? item : -item; // random +/-
});
Map函數不會修改您的數組,而只會返回新的映射數組(因此您必須重新分配它或將其分配給新變量)。
如何為正/負數添加第二個隨機數(翻轉硬幣):
var pos = Math.floor(Math.random()*10) % 2;
var num = Math.random() * 10;
var result;
// pos will evaluate false if it is 0
// or true if it is 1
result = pos ? num : -num;
return result;
當您是新手時,這是最簡單的方法。 用於循環和Math.floor()
math.random()*myArray.length
和for loop
生成一個隨機數,並更改與該數值對應的索引值,例如- for (i = 0; i < 10; i++){
var arrVal = myArray[Math.floor( Math.random()*myArray.length);]
if(arrVal > 0){
arrVal = arrVal*(-1);
};
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.