JavaScript中如何向类构造器传可变参数并实现统计类
Statistics Class Implementation in JavaScript
Constructor Handling for Variable Inputs
Yes, you can pass arrays to the constructor using spread syntax (...), and the constructor can accept variable-length inputs via rest parameters. Here’s a flexible setup that works for both individual values and direct array inputs:
class Statistics { constructor(...inputs) { // Handle case where an array is passed directly if (inputs.length === 1 && Array.isArray(inputs[0])) { this.data = inputs[0]; } else { this.data = inputs; } // Optional: Validate all inputs are numbers if (!this.data.every(num => typeof num === 'number')) { throw new Error('All inputs must be numeric values'); } } }
Usage Examples:
- Pass individual values:
const stats = new Statistics(26, 31, 27); - Pass an array using spread:
const stats = new Statistics(...ages); - Pass an array directly:
const stats = new Statistics(ages);
Method Implementation Best Practices
Store input data as a class property (this.data) so all methods can access it directly—no need to pass parameters to each method. Use built-in array methods like reduce, sort, and Math utilities instead of manual loops where possible for cleaner code.
Complete Statistics Class
Here’s the full implementation with all required statistical methods:
class Statistics { constructor(...inputs) { // Handle array input or individual values if (inputs.length === 1 && Array.isArray(inputs[0])) { this.data = inputs[0]; } else { this.data = inputs; } // Validate numeric inputs if (!this.data.every(num => typeof num === 'number')) { throw new Error('All inputs must be numeric values'); } } // Count of data points count() { return this.data.length; } // Sum of all values sum() { return this.data.reduce((acc, curr) => acc + curr, 0); } // Minimum value min() { return Math.min(...this.data); } // Maximum value max() { return Math.max(...this.data); } // Range (max - min) range() { return this.max() - this.min(); } // Mean (average) mean() { return this.sum() / this.count(); } // Median (middle value) median() { const sorted = [...this.data].sort((a, b) => a - b); const mid = Math.floor(sorted.length / 2); if (sorted.length % 2 === 0) { return (sorted[mid - 1] + sorted[mid]) / 2; } else { return sorted[mid]; } } // Mode (most frequent value) mode() { const frequency = this.data.reduce((acc, curr) => { acc[curr] = (acc[curr] || 0) + 1; return acc; }, {}); let maxCount = 0; let modeValue = null; for (const [num, count] of Object.entries(frequency)) { const numInt = parseInt(num); if (count > maxCount) { maxCount = count; modeValue = numInt; } } return { mode: modeValue, count: maxCount }; } // Population variance var() { const avg = this.mean(); const squaredDifferences = this.data.map(num => Math.pow(num - avg, 2)); return squaredDifferences.reduce((acc, curr) => acc + curr, 0) / this.count(); } // Standard deviation (square root of variance) std() { return Math.sqrt(this.var()); } // Frequency distribution (percentage, value) sorted by percentage descending freqDist() { const total = this.count(); const frequency = this.data.reduce((acc, curr) => { acc[curr] = (acc[curr] || 0) + 1; return acc; }, {}); // Convert to array of [percentage, value] and sort return Object.entries(frequency) .map(([num, count]) => [(count / total) * 100, parseInt(num)]) .sort((a, b) => b[0] - a[0]); } // Describe all statistics in readable format describe() { const mode = this.mode(); const freqDist = this.freqDist().map(item => `(${item[0].toFixed(1)}, ${item[1]})`).join(', '); console.log(`Count: ${this.count()}`); console.log(`Sum: ${this.sum()}`); console.log(`Min: ${this.min()}`); console.log(`Max: ${this.max()}`); console.log(`Range: ${this.range()}`); console.log(`Mean: ${this.mean().toFixed(1)}`); console.log(`Median: ${this.median()}`); console.log(`Mode: (${mode.mode}, ${mode.count})`); console.log(`Variance: ${this.var().toFixed(1)}`); console.log(`Standard Deviation: ${this.std().toFixed(1)}`); console.log(`Frequency Distribution: [${freqDist}]`); } }
Example Usage
const ages = [31, 26, 34, 37, 27, 26, 32, 32, 26, 27, 27, 24, 32, 33, 27, 25, 26, 38, 37, 31, 34, 24, 33, 29, 26]; const statistics = new Statistics(ages); // Individual method calls console.log('Count:', statistics.count()); // 25 console.log('Sum: ', statistics.sum()); // 744 console.log('Min: ', statistics.min()); // 24 console.log('Max: ', statistics.max()); // 38 console.log('Range: ', statistics.range()); // 14 console.log('Mean: ', statistics.mean().toFixed(1)); // 30.0 console.log('Median: ', statistics.median()); // 29 console.log('Mode: ', statistics.mode()); // { mode: 26, count: 5 } console.log('Variance: ', statistics.var().toFixed(1)); // 17.5 console.log('Standard Deviation: ', statistics.std().toFixed(1)); // 4.2 console.log('Frequency Distribution: ', statistics.freqDist()); // Full description statistics.describe();
Output of describe():
Count: 25 Sum: 744 Min: 24 Max: 38 Range: 14 Mean: 30.0 Median: 29 Mode: (26, 5) Variance: 17.5 Standard Deviation: 4.2 Frequency Distribution: [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)]
内容的提问来源于stack exchange,提问作者web-innov-design
相关产品推荐
相关产品推荐

