根据长度创建对象数组;每个对象都有一个属性,其值为index+1
我想将我丑陋的代码改进为更干净和简单的东西。如何缩短此代码?
if (this.foo < 2) {
return (this.result = [ { year: 1 } ]);
}
if (this.foo < 3) {
return (this.result = [ { year: 1 }, { year: 2 } ]);
}
if (this.foo < 4) {
return (this.result = [ { year: 1 }, { year: 2 }, { year: 3 } ]);
}
if (this.foo < 5) {
return (this.result = [ { year: 1 }, { year: 2 }, { year: 3 }, { year: 4 } ]);
}
if (this.foo < 6) {
return (this.result = [ { year: 1 }, { year: 2 }, { year: 3 }, { year: 4 }, { year: 5 } ]);
}
回答
创建一个数组Array,并使用Array.prototype.map。
function func(foo) {
return Array(foo).fill().map((f, i) => ({ year: i + 1 }));
}
console.log(func(1));
console.log(func(3));