这更像是一个愚蠢的问题,但我不得不问。 调用map之类的不带参数的数组函数是一种好习惯吗? 假设我的代码上已经有一个指定长度的数组“ x”,并且我想制作另一个长度相同但内容不同的数组。 例如:
function generateRandomContent() { ... }
const x = [1, 2, 3, 4, 5]
const y = x.map(() => generateRandomContent())
// or
const z = Array(x.length).fill().map(() => { ... })
我当然可以传递参数而从不使用它,但是这样做有好方法又有坏方法吗?
答案 0 :(得分:1)
您不应在此处使用.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(''))
如果您只想基于原始的 length 创建一个新数组,但内容完全不相关,那么最好使用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);