问题
I am using the faker.js
library to generate random data and I have a couple of factory functions that generate a series of user data:
const createUser = () => {
return {
name: faker.name.findName(),
email: faker.internet.email(),
address: faker.address.streetAddress(),
bio: faker.lorem.sentence(),
image: faker.image.avatar(),
};
};
const createUsers = (numUsers = 5) => {
return Array(numUsers).fill(createUser());
};
let fakeUsers = createUsers(5);
console.log(fakeUsers);
The problem with this Array.fill
approach is that it returns the same data n
number of times. I want 5
different users to be returned from my factory.
How do I do this?
回答1:
Array.from allows you to create an array and initialize it with values returned from a callback function in one step:
const createUsers = (numUsers = 5) => {
return Array.from({length: numUsers}, createUser);
}
回答2:
Create an array with blanks, and then use .map()
to create users:
const createUsers = (numUsers = 5) => {
return Array(numUsers)
.fill(null)
.map(createUser);
}
回答3:
Creating an array via the Array constructor will yield an non mappable (or iterable for that matter) array.
This happens because the constructor will give you an array with X uninitialized values, causing map to fail. Using fill to initialize the values, even if initialized to null
or undefined
, will work:
const createUser = () => {
return {
name: faker.name.findName(),
email: faker.internet.email(),
address: faker.address.streetAddress(),
bio: faker.lorem.sentence(),
image: faker.image.avatar()
}
}
const createUsers = (numUsers = 5) => {
return new Array(numUsers)
.fill(undefined)
.map(createUser);
}
let fakeUsers = createUsers(5)
console.log(fakeUsers)
https://jsbin.com/punesorico/edit?html,js,console
回答4:
Here is another way of doing this job by a TCO recursive function;
function getFakeObject(){
return Array(5).fill()
.reduce(o => Object.assign(o,{[String.fromCharCode(...Array(5).fill().map(_ => ~~(Math.random()*26)+65))] : String.fromCharCode(...Array(5).fill().map(_ => ~~(Math.random()*26)+97))}),{});
}
function makeFakeObjectsArray(n, r = []){
return n ? makeFakeObjectsArray(n-1,(r.push(getFakeObject()),r)) : r;
}
console.log(makeFakeObjectsArray(5));
来源:https://stackoverflow.com/questions/42861732/generate-an-array-with-random-data-without-using-a-for-loop