JavaScript 数组操作和数学计算

计算数组平均值

使用 reduce 方法

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
const average = sum / numbers.length;
console.log(average); // 输出: 3

使用 forEach 方法

const numbers = [1, 2, 3, 4, 5];
let sum = 0;
numbers.forEach(number => sum += number);
const average = sum / numbers.length;
console.log(average); // 输出: 3

使用 mapreduce 方法

const numbers = [1, 2, 3, 4, 5];
const sumAndCount = numbers.reduce((acc, val) => {
  acc.sum += val;
  acc.count++;
  return acc;
}, { sum: 0, count: 0 });
const average = sumAndCount.sum / sumAndCount.count;
console.log(average); // 输出: 3

获取数组最大值

使用 Math.maxapply

const numbers = [1, 2, 3, 4, 5];
const max = Math.max.apply(null, numbers);
console.log(max); // 输出: 5

使用 Math.max 和扩展运算符

const numbers = [1, 2, 3, 4, 5];
const max = Math.max(...numbers);
console.log(max); // 输出: 5

使用 reduce 方法

const numbers = [1, 2, 3, 4, 5];
const max = numbers.reduce((a, b) => Math.max(a, b));
console.log(max); // 输出: 5

使用 sort 方法

const numbers = [1, 2, 3, 4, 5];
numbers.sort((a, b) => b - a);
const max = numbers[0];
console.log(max); // 输出: 5

使用 for 循环

const numbers = [1, 2, 3, 4, 5];
let max = numbers[0];
for(let i = 1; i < numbers.length; i++) {
  if(numbers[i] > max) {
    max = numbers[i];
  }
}
console.log(max); // 输出: 5

计算次方

使用 Math.pow

const base = 2;
const exponent = 3;
const result = Math.pow(base, exponent);
console.log(result); // 输出: 8

使用 ** 运算符

const base = 2;
const exponent = 3;
const result = base ** exponent;
console.log(result); // 输出: 8

获取二维数组内层最小数组的长度

const arrayOfArrays = [[1, 2, 3], [1, 2], [1, 2, 3, 4, 5], [1]];
const minLength = arrayOfArrays.reduce((min, arr) => {
  return Math.min(min, arr.length);
}, Infinity);
console.log(minLength); // 输出: 1

或者使用 mapMath.min

const arrayOfArrays = [[1, 2, 3], [1, 2], [1, 2, 3, 4, 5], [1]];
const lengths = arrayOfArrays.map(arr => arr.length);
const minLength = Math.min(...lengths);
console.log(minLength); // 输出: 1

以上内容涵盖了在 JavaScript 中对数组进行操作和计算的一些基本知识点。

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值