const data = [];
Array.from({ length: 1 }).forEach(() => {
data.push({
number: Math.floor(Math.random() * 10)
});
});
console.log(data)
我使用上面的代码生成对象数组,但我使用数据作为临时变量,不确定是否可以写得更好。
最佳答案
您不需要 forEach
调用。 Array.from()
接受回调函数作为第二个参数:
const data = Array.from(
{ length: 3 },
() => ({ number: Math.floor(Math.random() * 10) }),
);
console.log(data);
关于javascript - 避免在 array.from 中使用临时变量的一个衬垫?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74847504/