我实现了一种生成带有可重复计数且前缀为0的项目列表的方法。生成此类列表的最佳方法是什么?
当前行为:
const generateList = (length, n, i) => {
let b = n+i
return b.toString().padStart(length.toString().length + n.toString.length, 0)
}
Array(10).fill(null).map((x, i) => generateList(10,2, i))
输出结果:
["002", "003", "004", "005", "006", "007", "008", "009", "010", "011"]
您是否有其他想法?
答案 0 :(得分:2)
您可以确定开始时需要的字符数,并使用预定值来格式化数组的输出。
function createList(startValue, endValue) {
let
// The minimum output length, for a single digit number, is 2 chars.
outputLength = 2,
testValue = 10,
// Create an empty array which has as many items as numbers we need to
// generate for the output. Add 1 to the end value as this is to be
// inclusive of the range to create. If the +1 is not done the resulting
// array is 1 item too small.
emptyArray = Array(endValue - startValue + 1);
// As long as test value is less than the end value, keep increasing the
// output size by 1 and continue to the next multiple of 10.
while (testValue <= endValue) {
outputLength++;
testValue = testValue * 10;
}
// Create a new array, with the same length as the empty array created
// earlier. For each position place a padded number into the output array.
return Array.from(emptyArray, (currentValue, index) => {
// Pad the current value to the determined max length.
return (startValue + index).toString().padStart(outputLength, '0');
});
}
function createListWithLength(length, startValue = 0) {
return createList(startValue, startValue + length);
}
console.log(createList(2,10));
console.log(createListWithLength(30));
console.log(createListWithLength(10, 995));
答案 1 :(得分:1)
看看发电机:
function* range(from, to) {
for (var i=from; i<to; i++)
yield i;
}
function* paddedRange(from, to) {
const length = (to-1).toString(10) + 1 /* at least one pad */;
for (const i of range(from, to))
yield i.padStart(length, '0');
}
console.log(Array.from(paddedRange(2, 12)));
您也可以将循环从range
插入paddedRange
,或者可以使其直接返回数组:
function paddedRange(from, to) {
const length = (to-1).toString(10) + 1 /* at least one pad */;
return Array.from(range(from, to), i => i.padStart(length, '0'));
}
console.log(paddedRange(2, 12));
主要的简化是,您应该只计算一次填充长度,并为其指定一个命名性名称,而不是针对每个数字再次计算。另外,范围通常由下端和上端给出,而不是由开始和长度给出,但是如果出于某些原因需要后者,则可以轻松切换回去。
答案 2 :(得分:0)
不确定,但也许是这样
const generateList = length => Array(length).fill('0').map((item, index) => item + index);
console.log(generateList(20));