使用js写一个方法生成0000-9999一万个数字(4位数)
function generateFourDigitNumbers() {
const numbers = [];
for (let i = 0; i <= 9999; i++) {
// Use padStart to ensure each number is 4 digits long
const numberString = i.toString().padStart(4, '0');
numbers.push(numberString);
}
return numbers;
}
// Example usage:
const fourDigitNumbers = generateFourDigitNumbers();
console.log(fourDigitNumbers); // Output: ['0000', '0001', '0002', ..., '9999']
// If you need the numbers as actual numbers (integers) instead of strings:
function generateFourDigitNumbersAsIntegers() {
const numbers = [];
for (let i = 0; i <= 9999; i++) {
numbers.push(i);
}
return numbers;
}
const integerNumbers = generateFourDigitNumbersAsIntegers();
// More efficient version using Array.from and keys method (for strings):
const fourDigitNumbersEfficient = Array.from({ length: 10000 }, (_, i) => i.toString().padStart(4, '0'));
// More efficient version for integers:
const fourDigitIntegersEfficient = Array.from({ length: 10000 }, (_, i) => i);
// If you need to frequently generate ranges of four-digit numbers, a generator function can be more memory-efficient:
function* fourDigitNumberGenerator(start = 0, end = 9999) {
for (let i = start; i <= end; i++) {
yield i.toString().padStart(4, '0'); // Or yield i for integers
}
}
// Example usage of the generator:
for (const num of fourDigitNumberGenerator(1000, 1010)) {
console.log(num); // Output: 1000, 1001, ..., 1010
}
// To get an array from the generator:
const generatedArray = [...fourDigitNumberGenerator()];
This provides several options, including more efficient methods using Array.from
and a generator function for cases where memory efficiency is a primary concern. Choose the version that best suits your specific needs. The generator is particularly useful if you don't need all the numbers at once but want to iterate through them one by one. Also included are versions that produce integers instead of strings, as well as a generator that allows you to specify the start and end of the range.