简体   繁体   English

从 random() 生成器创建一个新数组?

[英]Create a new array from a random() generator?

I'm trying to create a new array with 5 random names taken from an array with 897 names.我正在尝试创建一个新数组,其中包含 5 个随机名称,这些名称取自具有 897 个名称的数组。 This is what I tried to do but I'm not sure how to specify that I only want 5 names:这就是我试图做的,但我不确定如何指定我只想要 5 个名字:

for(let i = 0; i < pokemon.all().length; i++){
    pokedex = [i];
};
app.get('/dex', (req, res) => {
    res.send(pokedex)
});

Take a look at this, use Math.random() to generate random index and get it from pokemons array, then unset the value from pokemons to have no doublon in pokedex.看看这个,使用Math.random()生成随机索引并从 pokemons 数组中获取它,然后将 pokemons 中的值取消设置为 pokedex 中没有双倍。

 let pokemons = ['pika1','pika2','pika3','pika4','pika5','pika6','pika7'] let pokedex = []; for (i = 0; i < 5; i++) { id = Math.floor(Math.random() * pokemons.length); pokedex.push(pokemons[id]); pokemons.splice(id, 1); } //app.send() here... console.log(pokedex)

EDIT: Considering you have a pokemon.random() generator(?) in this npm package.编辑:考虑到你在这个 npm 包中有一个pokemon.random() generator(?) Simply use:只需使用:

let pokedex = [];
for(let i = 0; i < 5; i++)    
    pokedex.push(pokemon.random()) };
app.get('/dex', (req, res) => {     
        res.send(pokedex) 
});

 function pickNOf(list, n) { // - create a new shallow array copy. // - does decouple the original reference, thus it // prevents its further mutation by eg `splice`. list = Array.from(list); return Array // - creates an iterable array of the desired length ... .from({ length: n }) // ... thus it can be iterated by eg `map` or `flatMap`. .flatMap(() => // - `splice` does mutate the list by removing a // single item from its randomly chosen index. list.splice(Math.floor(Math.random() * list.length), 1) ); } const listOfAllPokemonNames = [ "Bulbasaur", "Ivysaur", "Venusaur", "Charmander", "Charmeleon", "Charizard", "Squirtle", "Wartortle", "Blastoise", "Caterpie", "Metapod", "Butterfree", "Weedle", "Kakuna", "Beedrill", "Pidgey" ]; console.log( "pickNOf(listOfAllPokemonNames, 5) ...", pickNOf(listOfAllPokemonNames, 5) ); console.log( "pickNOf(listOfAllPokemonNames, 9) ...", pickNOf(listOfAllPokemonNames, 9) ); console.log( "pickNOf(listOfAllPokemonNames, 3) ...", pickNOf(listOfAllPokemonNames, 3) );
 .as-console-wrapper { min-height: 100%!important; top: 0; }

Usage within the OP's code then does look like this ... OP 代码中的用法看起来像这样......

function pickNOf(list, n) {
  list = Array.from(list);
  return Array
    .from({ length: n })
    .flatMap(() =>
      list.splice(Math.floor(Math.random() * list.length), 1)
    );
}

app.get('/dex', (req, res) => {
  res.send(pickNOf(pokemon.all(), 5))
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM