英文:
Alternative code for filling an array with a series incremented by any value
问题
以下是已翻译的代码部分:
private seriesIncrementedBy5(upperLimit: number): number[] {
const series = [];
for (let s = 5; s <= upperLimit + 5; s += 5) {
series.push(s);
}
return series;
}
请注意,我只提供了代码的翻译部分,没有其他内容。
英文:
The following typescript function seriesIncrementedBy5
returns an array with numbers starting from 5 to upperLimit
with an increment of 5.
Is there a way to replace this 5 lines of code with any recent typescript ES6 advanced function which will take less than 5 lines.
private seriesIncrementedBy5(upperLimit: number): number[] {
const series = [];
for (let s = 5; s <= upperLimit + 5; s += 5) {
series.push(s);
}
return series;
}
答案1
得分: 2
您可以使用 Array.from 方法,该方法可以接受一个带有 length: number
属性和第二个参数用于填充的对象:
const seriesIncrementedBy5 = (upperLimit: number): number[] =>
Array.from({ length: Math.floor(upperLimit / 5) + 1 }, (_, i) => (i + 1) * 5);
为了计算数组的长度,我们将 upperLimit
除以 5
并向下取整得到一个整数;关键是要添加 + 1
以包含 upperLimit
在数组中。对于填充部分,我们将使用元素的索引;因为我们从 5
开始,而不是 0
,所以我们将索引加上 + 1
,然后乘以 5
。
英文:
You can use Array.from, which can accept an object with the length: number
property and a second argument populating function:
const seriesIncrementedBy5 = (upperLimit: number): number[] =>
Array.from({ length: Math.floor(upperLimit / 5) + 1 }, (_, i) => (i + 1) * 5);
To calculate the length, we divide the upperLimit
by 5
and floor it to get an integer; it is crucial to add + 1
to include the upperLimit
in the array. To populate, we will use the element's index; since we are starting from 5
, not 0
, we will add + 1
to the index and multiply it by 5
.
答案2
得分: 1
你可以创建一个正确大小的数组,然后使用 map
进行操作。
const seriesIncrementedBy5 = upperLimit => [...Array((upperLimit/5|0)+1)]
.map((_, i) => 5 * (i + 1));
console.log(seriesIncrementedBy5(10));
console.log(seriesIncrementedBy5(9));
英文:
You can create an array of the correct size and then map
over it.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const seriesIncrementedBy5 = upperLimit => [...Array((upperLimit/5|0)+1)]
.map((_, i) => 5 * (i + 1));
console.log(seriesIncrementedBy5(10));
console.log(seriesIncrementedBy5(9));
<!-- end snippet -->
答案3
得分: 1
你可以使用 Array.from
方法。
private seriesIncrementedBy5(upperLimit: number): number[] {
return Array.from({ length: Math.floor(upperLimit / 5) }, (_, i) => (i + 1) * 5);
}
更多信息可以查看这里。
英文:
You can use the Array.from
method.
private seriesIncrementedBy5(upperLimit: number): number[] {
return Array.from({ length: Math.floor(upperLimit / 5) }, (_, i) => (i + 1) * 5);
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论