自学内容网 自学内容网

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 中对数组进行操作和计算的一些基本知识点。


原文地址:https://blog.csdn.net/weixin_45596561/article/details/139771773

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!