这更像是一个愚蠢的问题,但我必须问它。在没有参数的情况下调用像map这样的数组函数是一个很好的实践吗?假设我的代码中已经有一个具有指定长度的数组'x‘,我想要创建另一个具有相同长度但内容不同的数组。例如:
function generateRandomContent() { ... }
const x = [1, 2, 3, 4, 5]
const y = x.map(() => generateRandomContent())
// or
const z = Array(x.length).fill().map(() => { ... })当然,我可以通过一个论点,但从来不使用它,但它有一个好的方法和一个不好的方式来做它?
发布于 2019-12-27 14:59:20
您不应该在这里使用.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);
https://stackoverflow.com/questions/59502329
复制相似问题