javascript - 使用 array.from 时如何用一行代码避免使用临时变量?
const data = [];
Array.from({ length: 1 }).forEach(() => {
data.push({
number: Math.floor(Math.random() * 10)
});
});
console.log(data)我使用上面的代码来生成对象数组,但我把 data 当作临时变量,不确定我是否可以写得更好。
答案#1
你不需要调用 forEach。Array.from() 接受一个回调函数作为第二个参数:
const data = Array.from(
{ length: 3 },
() => ({ number: Math.floor(Math.random() * 10) }),
);
console.log(data);