/** * Generate a sequence that specifies the start and end values * similar Python Of range function * @param {Number} start Starting value * @param {Number} end End value * @param {Number} step step * @returns {Array} Sequence * eg: * range(2011, 2022); * * [ * 2011, 2012, 2013, * 2014, 2015, 2016, * 2017, 2018, 2019, * 2020, 2021, 2022 * ] */
function range(start, end, step = 1) {
let current = start;
let list = [];
while (current <= end) {
list.push(current);
current += step;
}
return list;
}
Application example : Generate a 2020 To 2022 Sequence of years
let list = range(2020, 2022).map(val => {
return {
label: val + '',
value: val + ''
};
});
console.log(list);
// [
// { label: '2020', value: '2020' },
// { label: '2021', value: '2021' },
// { label: '2022', value: '2022' }
// ]
Using the function library lodash Provided range Method
// demo.cjs
// node v10.16.0
// npm i lodash -S
import lodash from 'lodash';
// Be careful : there lodash The value range is [2020, 2023)
let list = lodash.range(2020, 2023).map(val => {
return {
label: val + '',
value: val + ''
};
});
console.log(list);
// [
// { label: '2020', value: '2020' },
// { label: '2021', value: '2021' },
// { label: '2022', value: '2022' }
// ]
file :https://www.lodashjs.com/docs/lodash.range