用Javascript数组替换随机项 [英] Substitute random items in a Javascript array

查看:87
本文介绍了用Javascript数组替换随机项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中,我试图将数组中一半(在6种中的3种)中的项随机替换为不同项(所有类型均相同),我需要保留原始项的位置。因此,举例来说,如果我有:

In Javascript, am trying to randomly substitute half (in this case, 3 out of 6) of the items from an array with different ones (all of the same type), and I need the original items' position to be kept. So for instance, if I have:

var my_array = [a, b, c, d, e, f]

我想选择三个随机数替换为0,而其他两个保持初始位置。因此,假设a,c和d是随机选择器将在一个实例上消失的那些,则我的数组将变为:

I would want to select three random ones to be substituted with a 0, while the others to keep their initial position. So let's say a, c, and d are the ones the random selector will make go away on one instance, then my array would become:

my_array = [0, b, 0, 0, e, f]

在另一轮中,随机选择器可能会选择b,c和f,所以我会得到:

On a different run, the random selector would perhaps pick b, c, and f and so I'd have:

my_array = [a, 0, 0, d, e, 0]

,依此类推。
非常感谢您的帮助!

And so on. Thank you so much for your help!

推荐答案

您可以对数组进行闭包处理,并希望零计数和返回一个函数,该函数生成随机整数并将数组与零或值映射。

You could take a closure over the array and wanted zero counts and return a function which generates random integer and map the array with zeros or values.

function getRandom(array, count) {
    return function () {
        const indices = new Set();
        do {
            indices.add(Math.floor(Math.random() * array.length));
        } while (indices.size < count)
        return array.map((v, i) => indices.has(i) ? 0 : v);
    };
}

var myArray = ['a', 'b', 'c', 'd', 'e', 'f'],
    getArrayWithZeros = getRandom(myArray, 3);


console.log(...getArrayWithZeros());
console.log(...getArrayWithZeros());
console.log(...getArrayWithZeros());
console.log(...getArrayWithZeros());
console.log(...getArrayWithZeros());

这篇关于用Javascript数组替换随机项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆