如何更改javascript数组中随机值的值?

时间:2020-10-11 11:08:40

标签: javascript arrays random

我正在通过函数接收具有已定义值和其他待定义值的数组。


["y", null, null, null, null, null, null, null, null]

我想做的是,每次接收到此数组时,我都会检查为空的值,并以随机方式选择其中之一,我想设置值“ Z”并返回数组修改。

为此,我在函数中执行以下操作:

    nextValue(array) {
        
        const random = Math.floor(Math.random() * array.length);        
    }
};

在这一点上,如果我打印值“ random = Nan”,则可以在其他参考文献中找到 和“ array [random] =未定义”。

如何修改值?

是否有一种更好的方法,而无需提取值并直接对其进行修改?

3 个答案:

答案 0 :(得分:2)

目前还不清楚您到底想要什么。假设任务是“使用元素null和其他一些值组成的数组,将一个随机的null翻转到某个预设字符串,然后就位”,这就是您可能会使用的方法:

function flipRandomNull(arrayWithNulls, character) {
  const indexesOfNulls = arrayWithNulls.reduce((acc, item, index) => {
    return item === null ? [...acc, index] : acc;
  }, []);

  if (!indexesOfNulls.length) return; // no nulls for ya, nothing to flip

  const indexToFlip = indexesOfNulls[ Math.random() * indexesOfNulls.length | 0];
  arrayWithNulls[ indexToFlip ] = character;
}

const initialField = ["y", null, null, null, null, null, null, null, null];

[...Array(initialField.length - 1)].forEach(() => {
  flipRandomNull(initialField, 'Z');
  console.log(initialField.join(' | '));
});

答案 1 :(得分:2)

您可以使用array.map和array.filter方法找出数组中空项目的索引,然后用“ z”填充主数组的随机位置:

const arr = ["y", null, null, null, null, null, null, null, null];

const nextValue = (orgArr) => {
    const nullLocations = orgArr
        .map((item, idx) => (item === null ? idx : null))
        .filter((item) => item !== null);
    orgArr[nullLocations[Math.floor(Math.random() * nullLocations.length)]] = "z";
    return orgArr;
};

console.log(nextValue(arr));

答案 2 :(得分:0)

这是我的看法...

let arr = ["y", null, null, null, null, "y", null, null, null];
let size = arr.length;
// size of array

function random() {
  var random = Math.floor(Math.random() * size + 1)
  //generate radnom number betwen 0 and size of array
  if (arr[random] === null) {
    arr[random] = "z";
    // if random array  is null set z
    return size = 0;
    //stop loop
  } else {
    random = Math.floor(Math.random() * size + 1);
    // if not set new radnom number
  }
}

var i = 0;
while (i < size) {
  random()
  i++;
}
// loop function untill it sets radnom array null to z
console.log(arr)

加上更短的功能:

function random() {
  var random = Math.floor(Math.random() * size + 1)
  arr[random] === null ? (arr[random] = "z", size = 0 ) : (random = Math.floor(Math.random() * size + 1));  
}

let arr = ["y", null, "y", "y", null, "y", null, null, null];
let size = arr.length;


var i = 0;
while (i < size) {
  random()
  i++;
}

function random() {
  var random = Math.floor(Math.random() * size + 1)
  arr[random] === null ? (arr[random] = "z", size = 0, console.log("set, " + (i + 1) + " trys")) : (random = Math.floor(Math.random() * size + 1));
}


console.log(arr)
.as-console-wrapper {
  min-height: 100%
}