根据长度创建对象数组;每个对象都有一个属性,其值为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));


以上是根据长度创建对象数组;每个对象都有一个属性,其值为index+1的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>