This question already has answers here:
Create an array with random values
                            
                                (19个回答)
                            
                    
                在4个月前关闭。
        

    

这更像是一个愚蠢的问题,但我不得不问。
调用map之类的不带参数的数组函数是一种好习惯吗?
假设我的代码上已经有一个指定长度的数组“ x”,并且我想制作另一个长度相同但内容不同的数组。
例如:

function generateRandomContent() { ... }
const x = [1, 2, 3, 4, 5]
const y = x.map(() => generateRandomContent())
// or
const z = Array(x.length).fill().map(() => { ... })


当然,我可以传递一个参数并且永远不要使用它,但是这样做有好方法又有坏方法吗?

最佳答案

您不应在此处使用.map。映射操作是当您接受一些输入并生成新的输出时。因此,对于单个元素,您具有一个类似于此x -> y的关系,然后将其应用于整个数组以使用相同的映射规则生成一个新数组:



const input = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100];

//mapping relationship
const toCharacter = x => String.fromCharCode(x);

const result = input.map(toCharacter);

console.log(result.join(''))





如果您只是想基于原始长度创建一个新数组,但内容完全不相关,那么最好使用Array.from,它可以创建具有给定大小的数组并采用第二个参数填充该数组内容:



function generateRandomContent() {
  return Math.floor(Math.random() * 100);
}
const x = [1, 2, 3, 4, 5]

const y = Array.from({length: x.length}, () => generateRandomContent());
//or just pass the function reference
const z = Array.from({length: x.length}, generateRandomContent);


console.log(y);
console.log(z);

09-25 16:27
查看更多