Lodash提供了丰富的数值计算方法,以下是关于Lodash数值计算的详细解答:
Lodash数值计算方法概述
Lodash提供了许多数值计算方法,用于处理数字集合、进行数学运算等。这些方法比原生的Math方法更强大、更灵活。
1. 基本数学运算
_.add(augend, addend)
两个数相加。
javascript_.add(6, 4); // => 10 // 实际应用:计算总和 function calculateTotal(prices) { return _.reduce(prices, (sum, price) => _.add(sum, price), 0); } const prices = [10, 20, 30, 40]; console.log(calculateTotal(prices)); // => 100
_.subtract(minuend, subtrahend)
两个数相减。
javascript_.subtract(6, 4); // => 2 // 实际应用:计算折扣价格 function calculateDiscountPrice(price, discount) { return _.subtract(price, discount); } console.log(calculateDiscountPrice(100, 20)); // => 80
_.multiply(multiplier, multiplicand)
两个数相乘。
javascript_.multiply(6, 4); // => 24 // 实际应用:计算总价 function calculateTotalPrice(price, quantity) { return _.multiply(price, quantity); } console.log(calculateTotalPrice(25, 4)); // => 100
_.divide(dividend, divisor)
两个数相除。
javascript_.divide(6, 4); // => 1.5 // 实际应用:计算平均值 function calculateAverage(numbers) { const sum = _.sum(numbers); return _.divide(sum, numbers.length); } console.log(calculateAverage([10, 20, 30, 40])); // => 25
2. 数值取整
_.ceil(number, [precision=0])
向上取整。
javascript_.ceil(4.006); // => 4 _.ceil(6.004, 2); // => 6.01 _.ceil(6040, -2); // => 6100 // 实际应用:计算页数 function calculatePageCount(totalItems, itemsPerPage) { return _.ceil(_.divide(totalItems, itemsPerPage)); } console.log(calculatePageCount(105, 10)); // => 11
_.floor(number, [precision=0])
向下取整。
javascript_.floor(4.006); // => 4 _.floor(0.046, 2); // => 0.04 _.floor(4060, -2); // => 4000 // 实际应用:计算折扣金额 function calculateDiscountAmount(price, discountRate) { return _.floor(_.multiply(price, discountRate), 2); } console.log(calculateDiscountAmount(99.99, 0.15)); // => 14.99
_.round(number, [precision=0])
四舍五入。
javascript_.round(4.006); // => 4 _.round(4.006, 2); // => 4.01 _.round(4060, -2); // => 4100 // 实际应用:格式化价格 function formatPrice(price) { return _.round(price, 2); } console.log(formatPrice(99.995)); // => 100.00
_.clamp(number, [lower], upper)
将数值限制在指定范围内。
javascript_.clamp(-10, -5, 5); // => -5 _.clamp(10, -5, 5); // => 5 // 实际应用:限制数值范围 function limitValue(value, min, max) { return _.clamp(value, min, max); } console.log(limitValue(150, 0, 100)); // => 100 console.log(limitValue(-50, 0, 100)); // => 0
3. 数值统计
_.sum(array)
计算数组中所有数字的总和。
javascript_.sum([4, 2, 8, 6]); // => 20 // 实际应用:计算订单总额 function calculateOrderTotal(order) { return _.sum(_.map(order.items, item => item.price * item.quantity)); } const order = { items: [ { price: 10, quantity: 2 }, { price: 20, quantity: 1 }, { price: 30, quantity: 3 } ] }; console.log(calculateOrderTotal(order)); // => 130
_.sumBy(array, [iteratee])
根据迭代器函数计算总和。
javascriptvar objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; _.sumBy(objects, function(o) { return o.n; }); // => 20 _.sumBy(objects, 'n'); // => 20 // 实际应用:计算对象数组属性总和 function calculateTotalSalary(employees) { return _.sumBy(employees, 'salary'); } const employees = [ { name: 'John', salary: 50000 }, { name: 'Jane', salary: 60000 }, { name: 'Bob', salary: 55000 } ]; console.log(calculateTotalSalary(employees)); // => 165000
_.mean(array)
计算数组中所有数字的平均值。
javascript_.mean([4, 2, 8, 6]); // => 5 // 实际应用:计算平均分数 function calculateAverageScore(scores) { return _.mean(scores); } console.log(calculateAverageScore([85, 90, 78, 92, 88])); // => 86.6
_.meanBy(array, [iteratee])
根据迭代器函数计算平均值。
javascriptvar objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; _.meanBy(objects, function(o) { return o.n; }); // => 5 _.meanBy(objects, 'n'); // => 5 // 实际应用:计算对象数组属性平均值 function calculateAverageAge(users) { return _.meanBy(users, 'age'); } const users = [ { name: 'John', age: 25 }, { name: 'Jane', age: 30 }, { name: 'Bob', age: 28 } ]; console.log(calculateAverageAge(users)); // => 27.666666666666668
_.max(array)
计算数组中的最大值。
javascript_.max([4, 2, 8, 6]); // => 8 _.max([]); // => undefined // 实际应用:查找最高分 function findHighestScore(scores) { return _.max(scores); } console.log(findHighestScore([85, 90, 78, 92, 88])); // => 92
_.maxBy(array, [iteratee])
根据迭代器函数计算最大值。
javascriptvar objects = [{ 'n': 1 }, { 'n': 2 }]; _.maxBy(objects, function(o) { return o.n; }); // => { 'n': 2 } _.maxBy(objects, 'n'); // => { 'n': 2 } // 实际应用:查找最高薪水的员工 function findHighestPaidEmployee(employees) { return _.maxBy(employees, 'salary'); } const employees = [ { name: 'John', salary: 50000 }, { name: 'Jane', salary: 60000 }, { name: 'Bob', salary: 55000 } ]; console.log(findHighestPaidEmployee(employees)); // => { name: 'Jane', salary: 60000 }
_.min(array)
计算数组中的最小值。
javascript_.min([4, 2, 8, 6]); // => 2 _.min([]); // => undefined // 实际应用:查找最低分 function findLowestScore(scores) { return _.min(scores); } console.log(findLowestScore([85, 90, 78, 92, 88])); // => 78
_.minBy(array, [iteratee])
根据迭代器函数计算最小值。
javascriptvar objects = [{ 'n': 1 }, { 'n': 2 }]; _.minBy(objects, function(o) { return o.n; }); // => { 'n': 1 } _.minBy(objects, 'n'); // => { 'n': 1 } // 实际应用:查找最低薪水的员工 function findLowestPaidEmployee(employees) { return _.minBy(employees, 'salary'); } const employees = [ { name: 'John', salary: 50000 }, { name: 'Jane', salary: 60000 }, { name: 'Bob', salary: 55000 } ]; console.log(findLowestPaidEmployee(employees)); // => { name: 'John', salary: 50000 }
4. 数值范围
_.range([start=0], end, [step=1])
创建一个包含从start到end(不包含)的数字数组。
javascript_.range(4); // => [0, 1, 2, 3] _.range(-4); // => [0, -1, -2, -3] _.range(1, 5); // => [1, 2, 3, 4] _.range(0, 20, 5); // => [0, 5, 10, 15] _.range(0, -4, -1); // => [0, -1, -2, -3] // 实际应用:生成分页数组 function generatePageNumbers(totalPages, currentPage) { const range = 5; const start = Math.max(1, currentPage - Math.floor(range / 2)); const end = Math.min(totalPages, start + range); return _.range(start, end + 1); } console.log(generatePageNumbers(10, 5)); // => [3, 4, 5, 6, 7]
_.rangeRight([start=0], end, [step=1])
类似于_.range,但从右到左生成。
javascript_.rangeRight(4); // => [3, 2, 1, 0] _.rangeRight(-4); // => [-3, -2, -1, 0] _.rangeRight(1, 5); // => [4, 3, 2, 1] _.rangeRight(0, 20, 5); // => [15, 10, 5, 0]
5. 数值随机
_.random([lower=0], [upper=1], [floating])
生成一个随机数。
javascript_.random(0, 5); // => an integer between 0 and 5 _.random(5); // => also an integer between 0 and 5 _.random(5, true); // => a floating-point number between 0 and 5 _.random(1.2, 5.2); // => a floating-point number between 1.2 and 5.2 // 实际应用:生成随机ID function generateRandomId() { return _.random(100000, 999999); } console.log(generateRandomId()); // => 543210 // 实际应用:随机选择 function randomPick(array) { const index = _.random(0, array.length - 1); return array[index]; } const items = ['apple', 'banana', 'orange', 'grape']; console.log(randomPick(items)); // => 随机选择一个水果
6. 数值比较
_.inRange(number, [start=0], end)
检查数字是否在指定范围内。
javascript_.inRange(3, 2, 4); // => true _.inRange(4, 8); // => true _.inRange(4, 2); // => false _.inRange(2, 2); // => false _.inRange(1.2, 2); // => true _.inRange(5.2, 4); // => false // 实际应用:验证数值范围 function validateAge(age) { if (!_.inRange(age, 18, 65)) { throw new Error('Age must be between 18 and 65'); } return age; } console.log(validateAge(25)); // => 25 console.log(validateAge(70)); // => Error: Age must be between 18 and 65
7. 数值工具
_.maxBy(array, [iteratee])
根据迭代器函数计算最大值。
javascriptvar objects = [{ 'n': 1 }, { 'n': 2 }]; _.maxBy(objects, function(o) { return o.n; }); // => { 'n': 2 } _.maxBy(objects, 'n'); // => { 'n': 2 }
_.minBy(array, [iteratee])
根据迭代器函数计算最小值。
javascriptvar objects = [{ 'n': 1 }, { 'n': 2 }]; _.minBy(objects, function(o) { return o.n; }); // => { 'n': 1 } _.minBy(objects, 'n'); // => { 'n': 1 }
_.inRange(number, [start=0], end)
检查数字是否在指定范围内。
javascript_.inRange(3, 2, 4); // => true _.inRange(4, 8); // => true _.inRange(4, 2); // => false
实际应用示例
统计分析器
javascriptclass StatisticsAnalyzer { constructor(data) { this.data = data; } getSum() { return _.sum(this.data); } getMean() { return _.mean(this.data); } getMax() { return _.max(this.data); } getMin() { return _.min(this.data); } getRange() { return _.subtract(this.getMax(), this.getMin()); } getStatistics() { return { sum: this.getSum(), mean: this.getMean(), max: this.getMax(), min: this.getMin(), range: this.getRange(), count: this.data.length }; } } const scores = [85, 90, 78, 92, 88, 76, 95, 82]; const analyzer = new StatisticsAnalyzer(scores); console.log(analyzer.getStatistics()); // => { // sum: 686, // mean: 85.75, // max: 95, // min: 76, // range: 19, // count: 8 // }
价格计算器
javascriptclass PriceCalculator { static calculateSubtotal(items) { return _.sumBy(items, item => _.multiply(item.price, item.quantity)); } static calculateTax(subtotal, taxRate) { return _.multiply(subtotal, taxRate); } static calculateDiscount(subtotal, discountRate) { return _.multiply(subtotal, discountRate); } static calculateTotal(subtotal, tax, discount) { const afterDiscount = _.subtract(subtotal, discount); return _.add(afterDiscount, tax); } static calculateOrderTotal(items, taxRate = 0.1, discountRate = 0) { const subtotal = this.calculateSubtotal(items); const tax = this.calculateTax(subtotal, taxRate); const discount = this.calculateDiscount(subtotal, discountRate); const total = this.calculateTotal(subtotal, tax, discount); return { subtotal: _.round(subtotal, 2), tax: _.round(tax, 2), discount: _.round(discount, 2), total: _.round(total, 2) }; } } const cart = [ { name: 'Product A', price: 29.99, quantity: 2 }, { name: 'Product B', price: 49.99, quantity: 1 }, { name: 'Product C', price: 19.99, quantity: 3 } ]; const orderTotal = PriceCalculator.calculateOrderTotal(cart, 0.08, 0.1); console.log(orderTotal); // => { // subtotal: 149.95, // tax: 11.996, // discount: 14.995, // total: 146.951 // }
数值范围验证器
javascriptclass RangeValidator { static validate(value, min, max, fieldName = 'Value') { if (!_.isNumber(value)) { throw new Error(`${fieldName} must be a number`); } if (!_.inRange(value, min, max + 1)) { throw new Error(`${fieldName} must be between ${min} and ${max}`); } return value; } static clamp(value, min, max) { return _.clamp(value, min, max); } static validateAge(age) { return this.validate(age, 18, 65, 'Age'); } static validateScore(score) { return this.validate(score, 0, 100, 'Score'); } static validatePercentage(percentage) { return this.validate(percentage, 0, 100, 'Percentage'); } } console.log(RangeValidator.validateAge(25)); // => 25 console.log(RangeValidator.clamp(150, 0, 100)); // => 100 console.log(RangeValidator.validateScore(85)); // => 85
总结
Lodash提供了丰富的数值计算方法,包括:
- 基本数学运算:
_.add、_.subtract、_.multiply、_.divide - 数值取整:
_.ceil、_.floor、_.round、_.clamp - 数值统计:
_.sum、_.sumBy、_.mean、_.meanBy、_.max、_.maxBy、_.min、_.minBy - 数值范围:
_.range、_.rangeRight - 数值随机:
_.random - 数值比较:
_.inRange
这些数值计算方法比原生的Math方法更强大、更灵活,支持处理数组和对象数组。在实际开发中,建议使用这些方法来进行数值计算,以提高代码的可读性和可维护性。