程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

JS: implement a python like range function to generate digital sequences

編輯:Python
/** * 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


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved